Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use $$updated when extending a firebase factory to run a getTotal() function like in the example?

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
  };
}]);
like image 576
EmptyPockets Avatar asked Dec 08 '14 17:12

EmptyPockets


1 Answers

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.

like image 65
Frank van Puffelen Avatar answered Nov 17 '22 09:11

Frank van Puffelen