Reputation: 103
I want to add dynamically values of element of JSON in AngularJS. Below is my HTML tag where I want to display it:
<tr>
<th class="right"> Ending Value<span class="subVal">:</span></th>
</tr>
<tr>
<td class="right">$21,50,868.06</td>
</tr>
Now for this ending value, I want that it should be the sum of retailAcctTotalBalance
elements of below json :
"acconnts": [{
"userName": null,
"retailAcctNumber": "574436368",
"retailAcctTotalBalance": 0.0
}, {
"userName": null,
"retailAcctNumber": "101215858",
"retailAcctTotalBalance": 2118639.38
}, {
"userName": null,
"retailAcctNumber": "101900352",
"retailAcctTotalBalance": 32228.68
}, {
"userName": null,
"retailAcctNumber": "574435165",
"retailAcctTotalBalance": 0.0
}]
Upvotes: 1
Views: 1274
Reputation: 171679
One approach, add a function in scope that outputs what you want from your model
$scope.total=function(){
var total=0;
angular.forEach($scope.accounts, function(account) {
total += acc.retailAcctTotalBalance;
});
return total;
});
In Markup:
<td class="right">{{ total() }} </td>
Now whenever an update is made to the data, angular watchers will run a digest cycle, on each digest cycle it will evaluate the scope function found in the markup
Another way is to watch the data and update a variable whenever it changes
$scope.total=0;
$scope.accounts={ /* data*/}
$scopw.$watch('accounts',function(newVal,oldVal){
if(newVal != undefined)
$scope.total = getTotal();
})
function getTotal(){
var total=0;
angular.forEach($scope.accounts, function(account) {
total += acc.retailAcctTotalBalance;
});
return total;
});
In Markup:
<td class="right">{{ total }} </td>
Upvotes: 0
Reputation: 6543
The easiest way to go:
In your html file, you can do:
<td class="right">{{ sum }} </td>
And, in your controller:
$scope.sum = 0;
$scope.accounts = { /* your json data */ };
angular.forEach($scope.accounts, function(acc, index) {
$scope.sum += acc.retailAcctTotalBalance;
});
Upvotes: 1