iyasu watts
iyasu watts

Reputation: 3

adding values from firebase

{
   "-Jc6dpVCNnCafhnkXAuu" : {
       "amount" : 2,
       "body" : "dsfsdvsd",
       "from" : "angular"
   },
   "-Jc6fWfxkENC0amyZsS_" : {
       "amount" : 2,
       "body" : "massage",
       "from" : "angular"
   }
}

This is an example of the data that I'm trying to parse through

I am trying to grab all the items and add up the "amount" values. For example I want the total to be 4. I want to do this in AngularJS but I'm not sure how to reference the objects and add up the "amount" values.

Upvotes: 0

Views: 591

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600141

One way to do this (with Firebase's Web/JavaScript API):

var ref = new Firebase('https://your.firebaseio.com/');
ref.on('value', function(snapshot) {
    var total = 0;
    snapshot.forEach(function(childSnapshot) {
        total += childSnapshot.val().amount;
    });
   console.log(total);
});

Doing this in Angular does not make it too different. But unless you share some of your code/markup, it will be hard to see what your problem is.

Hint: if you are having problems doing something, it often helps to get rid of extraneous technologies. So if your problem is adding up the values in Firebase, throw away all other technologies first and solve the problem for just Firebase (as I did above). But if your problem is how to display a calculated value in Angular, get rid of Firebase/AngularFire/Ionic and first figure out how to display a calculated value with just Angular.

Upvotes: 1

Related Questions