Is there a way for me to retrieve the data returned by $$updated or have $$updated trigger a function that I can then receive every time a task is marked as completed?
By the end of the day, I need to maintain a count of how many tasks users have finished. It appears that firebase offers methods for automatically syncing this data, but the specifics on how to achieve this are unclear to me. I've encountered issues with $watch and executing functions upon task completion. The approach outlined here seems promising, but I'm struggling to connect all the pieces together.
Check out a working plnkr of the code here: 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
};
}]);