AngularJS Todo with PouchDB (Promises version)
This is the AngularJS Todo example with a PouchDB backend. Here's the original example: http://jsfiddle.net/dakra/U3pVM/
by yoorek
HTML
<script src="http://download.pouchdb.com/pouchdb-nightly.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<h2>Todo</h2>
<div ng-controller="MainCtrl">
<div class="label label-primary">{{remaining()}} of {{todos.length}} remaining</div>[ <a href="" ng-click="removeDone()">Remove done</a> ]
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done" ng-click="updateTodo(todo)" /> <span ng-class="{done:todo.done}">{{todo.text}}</span>
</li>
</ul>
<form class="form-horizontal" ng-submit="addTodo()">
<input class="form-control" type="text" ng-model="todoText" size="30" placeholder="add new todo here" />
<input class="btn btn-primary form-control" type="submit" value="add" />
</form>
</div>
CSS
.done {
text-decoration: line-through;
color: grey;
font-style: italic;
}
JavaScript
function MainCtrl($scope) {
$scope.todos = [];
PouchDB('angularpouchtodo')
.then(function (db) {
$scope.pouchdb = db;
return db.allDocs();
})
.then(function (response) {
$scope.loadTodos(response.rows);
})
.catch (function (error) {
console.log(error);
});
$scope.loadTodos = function (todos) {
for (var i = 0; i < todos.length - 1; i++) {
var todo = todos[i];
$scope.pouchdb.get(todo.id)
.then(function (doc) {
$scope.$apply(function () {
$scope.todos.push(doc);
});
})
.catch (function (error) {
console.log(error);
});
}
}
$scope.addTodo = function () {
var newTodo = {
text: $scope.todoText,
done: false
};
$scope.todos.push(newTodo);
$scope.todoText = '';
$scope.pouchdb.post(newTodo);
};
$scope.updateTodo = function (todo) {
$scope.pouchdb.put(todo);
};
$scope.remaining = function () {
var count = 0;
angular.forEach($scope.todos, function (todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.removeDone = function () {
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function (todo) {
if (!todo.done) {
$scope.todos.push(todo);
} else {
$scope.removeTodo(todo);
}
});
};
$scope.removeTodo = function (todo) {
$scope.pouchdb.get(todo._id)
.then(function(doc){
return $scope.pouchdb.remove(doc);
})
.then(function (response) {
console.log(response);
})
.catch(function(error){
...