EmptyPockets
EmptyPockets

Reputation: 727

How can I total values from an object in an array using firebase and angularfire?

Update for a better question:

I was able to get the factory running properly and have it total a number out of the loop. Now I'm having trouble getting that number to show up in the view and having that number show up every time a new item is added/removed/updated in the list.

The "ListWithTotal" factory works exactly like in the documentation. I wasn't properly setting the ref variable.

Here's the latest relevant code:

//controller
$scope.total = TodoService.getTotalPoints();

//service
var todos = $firebase(ref, {arrayFactory: "ListWithTotal"}).$asArray();

  return {
    getTotalPoints:function(){
         todos.$loaded().then(function() {
        total = todos.getTotal();
        console.log(total);
        return total;
      });
    },

I can't get this to return total to the view or update when the points value change. Can anyone please provide some direction?

Upvotes: 0

Views: 1757

Answers (1)

Kato
Kato

Reputation: 40582

The AngularFire guide covers this exact example in the section on extending factories.

app.factory("ListWithTotal", ["$FirebaseArray", "$firebase", function($FirebaseArray, $firebase) {
  // create a new factory based on $FirebaseArray
  var TotalFactory = $FirebaseArray.$extendFactory({
    getTotal: function() {
      var total = 0;
      // the array data is located in this.$list
      angular.forEach(this.$list, function(rec) {
        total += rec.amount;
      });
      return total;
    }
  });
  return function(listRef) {
    // override the factory used by $firebase
    var sync = $firebase(ref, {arrayFactory: TotalFactory});
    return sync.$asArray(); // this will be an instance of TotalFactory
  }
}]);

Upvotes: 3

Related Questions