-
Notifications
You must be signed in to change notification settings - Fork 2
/
pouch-todo.js
102 lines (88 loc) · 2.37 KB
/
pouch-todo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
(function() {
'use strict';
var app = angular.module('app', []);
app.factory('pouch', function() {
var db = new PouchDB('ng-pouch');
// db.sync('http://x.x.x.x/ng-db', {
// live: true
// });
return db;
});
app.factory('util', ['$q', '$rootScope',
function($q, $rootScope) {
return {
resolve: function(value) {
$rootScope.$apply(function() {
return $q.when(value);
});
},
reject: function(error) {
$rootScope.$apply(function() {
return $q.reject(error);
});
}
};
}]);
app.factory('Todos', ['$rootScope','pouch', 'util',
function($rootScope, pouch, util) {
var todos = [];
pouch.changes({ live: true })
.on('change', function handleUpdate(change) {
if (!change.deleted) {
pouch.get(change.id).then(function(todo) {
$rootScope.$apply(function() {
todos.push(todo);
});
}, function(err) {
console.log(err);
});
} else {
for (var i = 0; i < todos.length; ++i) {
if (todos[i]._id === change.id) {
$rootScope.$apply(function() {
todos.splice(i, 1);
});
break;
}
}
}
});
return {
todos: todos,
add: function(text) {
return pouch.post({
type: 'todo',
text: text
}).then(util.resolve)
.catch(util.reject);
},
remove: function(todo) {
return pouch.get(todo._id)
.then(function(doc) {
return pouch.remove(doc)
.then(util.resolve, util.reject);
})
.catch(util.reject);
}
};
}]);
app.controller('TodoCtrl', ['$scope', 'Todos',
function($scope, Todos) {
$scope.todos = Todos.todos;
$scope.submit = function() {
if ($scope.text !== '')
Todos.add($scope.text).then(function(res) {
$scope.text = '';
})
.catch(function(reason) {
console.log(reason);
});
};
$scope.remove = function(todo) {
Todos.remove(todo)
.catch(function(reason) {
console.log(reason);
});
};
}]);
})();