【发布时间】:2015-02-06 09:52:51
【问题描述】:
我是否可以接收 $$updated 返回的内容,或者让 $$updated 运行一个函数,然后每次检查任务时我都可以从该函数接收?
归根结底,我需要统计用户完成了多少任务。似乎firebase有自动同步这些数据的方法,但目前还不清楚具体如何做到这一点。当任务完成时,我遇到了 $watch 和运行函数的问题。这看起来是一种有趣的方式,但我无法将这些部分组合在一起。
这里是下面代码的工作 plnkr:http://plnkr.co/edit/iAGvPHFWn2GSPGzBRpKh?p=preview
// Code goes here
angular.module('app', ['firebase']);
angular
.module('app')
.controller('main', function($scope, $firebase, $timeout, $window, ListWithTotal) {
var ref = new Firebase("https://plnkr.firebaseio.com");
$scope.listWithTotal = ListWithTotal(ref);
$scope.addTask = function(task) {
$scope.listWithTotal.$add({
title: task.title,
complete: false,
tally: 0
});
task.title = '';
};
$scope.completeTask = function(task) {
if (task.complete === true) {
task.complete = true;
task.tally = 1;
} else {
task.complete = false;
task.tally = 0;
}
$scope.listWithTotal.$save(task);
};
$scope.tallyCount = '';
//it would be cool if I can get tallyCount to receive
//the result of getTotal or automagically with $$updated.
}).factory("ListWithTotal", ["$FirebaseArray", "$firebase", function($FirebaseArray, $firebase) {
// create a new factory based on $FirebaseArray
var TotalFactory = $FirebaseArray.$extendFactory({
getTotal: function() {
var total = 0;
angular.forEach(this.$list, function(rec) {
total += rec.tally;
});
return total;
},
$$updated: function(){
return this.$list.getTotal();
}
});
return function(listRef) {
var sync = $firebase(listRef, {arrayFactory: TotalFactory});
return sync.$asArray(); // this will be an instance of TotalFactory
};
}]);
【问题讨论】:
标签: javascript angularjs firebase angularfire