-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathng-pouchdb-binding.js
70 lines (66 loc) · 2.07 KB
/
ng-pouchdb-binding.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
angular.module('pouchdb')
// This service binds the scope expression to a pouchdb/couchdb database.
// There is no promise provided
.factory('pouchBindingSimple', ['$timeout', '$parse', 'pouchdb', function($timeout, $parse, pouchDB) {
var stopTheWatch;
return function(reference, scope, expression) {
var getObj = $parse(expression);
var setObj = getObj.assign;
if (!setObj) {
throw new Error('expression ' + expression + 'must be assignable');
}
var database = pouchDB.create(reference);
database.get(expression).then(
function(res) {
setObj(scope, res);
},
function() {
newVal = angular.copy(getObj(scope));
database.put(newVal, expression).then(
function(res) {
newVal._rev = res.rev;
newVal._id = res.id;
setObj(newVal);
},
function(err) {
console.log(err);
})
});
function equalsIgnoreRev(val1, val2) {
var cleanVal1 = angular.copy(val1);
var cleanVal2 = angular.copy(val2);
cleanVal1._rev = null;
cleanVal2._rev = null;
return angular.equals(cleanVal1, cleanVal2);
}
database.changes({
live: true,
onChange: function(change) {
if (!change.deleted) {
database.get(change.id).then(
function(res) {
setObj(scope, res);
},
function(err) {
console.log(err);
});
}
}
});
var listener = function(ngValue) {
database.get(expression).then(
function(dbVal) {
if (!equalsIgnoreRev(dbVal, ngValue) && ngValue._id) {
database.put(angular.copy(ngValue)).then(
function(res) {
ngValue._rev = res.rev;
},
function(err) {
console.log(err);
});
}
});
};
stopTheWatch = scope.$watch(getObj, listener, true);
}
}]);