0

I feel like I am missing something basic here, and would love some help.

I have some data that looks like this

"playerPoints"{
    "ted":{"military":3,"gold":2},
    "bill":{"military":2,"gold":4}
}

And an ng-repeat that is player in playerPoints and it shows a list of each players points. But I want a total at the end of each list. That adds up all of that specific players points. In this instance ted would have 5 and bill would have 6.

I have looked around and haven't really come across something that seems like it would work, but this is where the missing basic info could come into play.

Any assistance would be grand.

  • 1
    What does this have to do with `ng-repeat`? You should be doing your calculations somewhere other than in the view. – isherwood Dec 02 '16 at 19:11
  • post some HTML code to see what you've tried. – rakemen Dec 02 '16 at 19:12
  • We don't need HTML. We need a controller or service function that does this and updates the object with a total points key/value pair. – isherwood Dec 02 '16 at 19:13
  • 1
    Possible duplicate of [How to sum the values of a JavaScript object?](http://stackoverflow.com/questions/16449295/how-to-sum-the-values-of-a-javascript-object) – isherwood Dec 02 '16 at 19:14

1 Answers1

1

You need a function in your controller or service that does this in advance. Something like this untested example:

myService.data = {
    "playerPoints": {
        "ted": {
            "military": 3,
            "gold": 2
        },
        "bill": {
            "military": 2,
            "gold": 4
        }
    }
};

function sum(obj) {
    var sum = 0;
    for (var el in obj) {
        if (obj.hasOwnProperty(el)) {
            sum += parseFloat(obj[el]);
        }
    }
    obj[el]["total"] = sum;
}

sum(myService.data.playerPoints);

In your controller you'll assign a variable to the service property:

ctrl.playerData = myService.data;

Then in your view you can simply output that key's value:

<div ng-repeat="player in ctrl.playerData">
    <span>{{player.total}}</span>
    ...
</div>

If done properly in a service and stored as a property of the service the view will be automatically data-bound and will update dynamically if the object's data changes.

isherwood
  • 58,414
  • 16
  • 114
  • 157