1

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
}]

2 Answers 2

1

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

good for initial controller load, won't update if/when data changes though
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.