Can I receive what is returned by $$updated or have $$updated run a function that I can then receive from every time a task is checked off?
At the end of the day, I need to keep a count of how many tasks users complete. It seems like firebase has ways of automatically syncing that data but it's unclear how to do that specifically. I've run into problems with $watch and running functions when a task is completed. This looks like an interesting way of doing it but I can't put the pieces together.
Here is working plnkr of the code below: 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
};
}]);
If you want an up-to-date tally of all completed tasks, you can add a then
to the point where you save the task:
$scope.listWithTotal.$save(task).then(function() {
$scope.tallyCount = $scope.listWithTotal.getTotal();
});
The then
block executes after the task has saved and adds the tally of completed tasks to the current scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With