Luigi Guarnuccio
Luigi Guarnuccio

Reputation: 21

Getting the sum of all values in object - ng-repeat

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.

Upvotes: 0

Views: 342

Answers (1)

isherwood
isherwood

Reputation: 61055

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.

Upvotes: 1

Related Questions