Sei sulla pagina 1di 8

IonicPouchdbToDoApp

V6.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>v6:ToDo - online</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/app.css" rel="stylesheet">
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/pouchdb/dist/pouchdb.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/v6.js"></script>
</head>
<body ng-app="todo" ng-controller="TodoCtrl">
<ion-header-bar class="bar-positive">
<h1 class="title">Todos</h1>
<!-- ########################################### -->
<!-- ### Add button for online toggle ### -->
<!-- ########################################### -->
<button class="button button-icon" ng-click="toggleOnline()">
<i class="icon" ng-class="{'ion-connection-bars' : online, 'ion-alert-circled' : !online}"></i>
</button>
<button class="button button-icon" ng-click="newTask()">
<i class="ion-compose icon"></i>
</button>
</ion-header-bar>
<ion-content>
<ion-list>
<ion-item ng-repeat="task in tasks" class="item-icon-right"
ng-class="{complete: task.completed}"
ng-click="completionChanged(task)">
<i class="icon ion-ios7-arrow-left"></i>
{{task.title}}
<ion-option-button class="button-energized" ng-click="editTitle(task)">
Edit
</ion-option-button>
<ion-option-button class="button-assertive" ng-click="delete(task)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
</ion-content>
<script id="new-task.html" type="text/ng-template">
<div class="modal">
<!-- Modal header bar -->

<ion-header-bar class="bar-secondary">
<h1 class="title">New Task</h1>
<button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>
</ion-header-bar>
<!-- Modal content area -->
<ion-content>
<form ng-submit="createTask(task)">
<div class="list">
<label class="item item-input">
<input type="text" placeholder="What do you need to do?" ng-model="task.title">
</label>
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive">Create Task</button>
</div>
</form>
</ion-content>
</div>
</script>
</body>
</html>

V6.js
angular.module('todo', ['ionic'])
// Simple PouchDB factory
.factory('todoDb', function() {
var db = new PouchDB('todos');
return db;
})
.controller('TodoCtrl', function($scope, $ionicModal, todoDb, $ionicPopup, $ionicListDelegate) {
// Initialize tasks
$scope.tasks = [];
////////////////////////
// Online sync to CouchDb
////////////////////////
$scope.online = false;
$scope.toggleOnline = function() {
$scope.online = !$scope.online;
if ($scope.online) { // Read http://pouchdb.com/api.html#sync
$scope.sync = todoDb.sync('http://127.0.0.1:5984/todos', {live: true})
.on('error', function (err) {
console.log("Syncing stopped");
console.log(err);
});
} else {
$scope.sync.cancel();
}
};
$scope.completionChanged = function(task) {
task.completed = !task.completed;
$scope.update(task);

};
todoDb.changes({
live: true,
onChange: function (change) {
if (!change.deleted) {
todoDb.get(change.id, function(err, doc) {
if (err) console.log(err);
$scope.$apply(function() { //UPDATE
for (var i = 0; i < $scope.tasks.length; i++) {
if ($scope.tasks[i]._id === doc._id) {
$scope.tasks[i] = doc;
return;
}
} // CREATE / READ
$scope.tasks.push(doc);
});
})
} else { //DELETE
$scope.$apply(function () {
for (var i = 0; i<$scope.tasks.length; i++) {
if ($scope.tasks[i]._id === change.id) {
$scope.tasks.splice(i,1);
}
}
})
}
}
});
$scope.update = function (task) {
todoDb.get(task._id, function (err, doc) {
if (err) {
console.log(err);
} else {
todoDb.put(angular.copy(task), doc._rev, function (err, res) {
if (err) console.log(err);
});
}
});
};
$scope.delete = function(task) {
todoDb.get(task._id, function (err, doc) {
todoDb.remove(doc, function (err, res) {});
});
};
$scope.editTitle = function (task) {
var scope = $scope.$new(true);
scope.data = { response: task.title } ;
$ionicPopup.prompt({
title: 'Edit task:',
scope: scope,
buttons: [
{ text: 'Cancel', onTap: function(e) { return false; } },
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function(e) {
return scope.data.response
}

},
]
}).then(function (newTitle) {
if (newTitle && newTitle != task.title) {
task.title = newTitle;
$scope.update(task);
}
$ionicListDelegate.closeOptionButtons();
});
};
// Create our modal
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope
});
$scope.createTask = function(task) {
task.completed = false;
todoDb.post(angular.copy(task), function(err, res) {
if (err) console.log(err)
task.title = "";
});
$scope.taskModal.hide();
};
$scope.newTask = function() {
$scope.taskModal.show();
};
$scope.closeNewTask = function() {
$scope.taskModal.hide();
};
});

Appngpouchdb.js
angular.module('todo', ['ionic','pouchdb'])
.controller('TodoCtrl', function($scope, $ionicModal, $ionicPopup, $ionicListDelegate, pouchCollection) {

////////////////////////
// Replace PouchDb database calls with pouchCollection
////////////////////////
$scope.todos = pouchCollection('todoslib');
$scope.online = false;
$scope.toggleOnline = function() {
$scope.online = !$scope.online;
if ($scope.online) { // Read http://pouchdb.com/api.html#sync
////////////////////////
// sync to CouchDb with pouchCollection reference
////////////////////////
$scope.sync = $scope.todos.$db.replicate.sync('http://127.0.0.1:5984/todoslib', {live: true})
.on('error', function (err) {

console.log("Syncing stopped");
console.log(err);
});
} else {
$scope.sync.cancel();
}
};
$scope.completionChanged = function(task) {
task.completed = !task.completed;
$scope.todos.$update(task);
};
$scope.delete = function(task) {
$scope.todos.$remove(task);
};
$scope.editTitle = function (task) {
var scope = $scope.$new(true);
scope.data = { response: task.title } ;
$ionicPopup.prompt({
title: 'Edit task:',
scope: scope,
buttons: [
{ text: 'Cancel', onTap: function(e) { return false; } },
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function(e) {
return scope.data.response
}
},
]
}).then(function (newTitle) {
if (newTitle && newTitle != task.title) {
task.title = newTitle;
$scope.todos.$update(task);
}
$ionicListDelegate.closeOptionButtons();
});
};
// Create our modal
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope
});
$scope.createTask = function(task) {
task.completed = false;
$scope.todos.$add(task);
console.log("Added "+task.title+" to todos");
$scope.taskModal.hide();
};
$scope.newTask = function() {
$scope.taskModal.show();
};
$scope.closeNewTask = function() {
$scope.taskModal.hide();

};
});

Ngpouchdbcollection.js
angular.module('pouchdb')
.factory('pouchCollection', ['$timeout', 'pouchdb', function($timeout, pouchdb) {
/**
* @class item in the collection
* @param item
* @param {int} index
position of the item in the collection
*
* @property {String} _id
unique identifier for this item within the collection
* @property {int} $index
position of the item in the collection
*/
function PouchDbItem(item, index) {
this.$index = index;
angular.extend(this, item);
}
/**
* create a pouchCollection
* @param {String} collectionUrl The pouchdb url where the collection lives
* @return {Array}
An array that will hold the items in the collection
*/
return function(collectionUrl) {
var collection = [];
var indexes = {};
var db = collection.$db = pouchdb.create(collectionUrl);
function getIndex(prevId) {
return prevId ? indexes[prevId] + 1 : 0;
}
function addChild(index, item) {
indexes[item._id] = index;
collection.splice(index,0,item);
console.log('added: ', index, item);
}
function removeChild(id) {
var index = indexes[id];
// Remove the item from the collection
collection.splice(index, 1);
indexes[id] = undefined;
console.log('removed: ', id);
}
function updateChild (index, item) {
collection[index] = item;
console.log('changed: ', index, item);

}
function moveChild (from, to, item) {
collection.splice(from, 1);
collection.splice(to, 0, item);
updateIndexes(from, to);
console.log('moved: ', from, ' -> ', to, item);
}
function updateIndexes(from, to) {
var length = collection.length;
to = to || length;
if ( to > length ) { to = length; }
for(index = from; index < to; index++) {
var item = collection[index];
item.$index = indexes[item._id] = index;
}
}
db.changes({live: true, onChange: function(change) {
if (!change.deleted) {
db.get(change.id).then(function (data){
if (indexes[change.id]==undefined) { // CREATE / READ
addChild(collection.length, new PouchDbItem(data, collection.length)); // Add to end
updateIndexes(0);
} else { // UPDATE
var index = indexes[change.id];
var item = new PouchDbItem(data, index);
updateChild(index, item);
}
});
} else { //DELETE
removeChild(change.id);
updateIndexes(indexes[change.id]);
}
}});
collection.$add = function(item) {
db.post(angular.copy(item)).then(
function(res) {
item._rev = res.rev;
item._id = res.id;
}
);
};
collection.$remove = function(itemOrId) {
var item = angular.isString(itemOrId) ? collection[itemOrId] : itemOrId;
db.remove(item)
};
collection.$update = function(itemOrId) {
var item = angular.isString(itemOrId) ? collection[itemOrId] : itemOrId;
var copy = {};
angular.forEach(item, function(value, key) {
if (key.indexOf('$') !== 0) {
copy[key] = value;
}
});
db.get(item._id).then(
function (res) {
db.put(copy, res._rev);
}

);
};
return collection;
};
}]);

App.css
.complete{
textdecoration:linethrough;
color:grey;
}

Potrebbero piacerti anche