Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculate the sum of values in ng repeat Angularjs

I am new to Angularjs. I am displaying list of items using ng-repeat. how to calculate the sum of it? is there any simple method to calculate it in html using expression?

name  numberofyears amount interest 
 xxx       2          4000   4%
 yyy       3          3000   10%
 zzz       5          6000    6%

 Total     10        13000   16%

First three rows are from ng repeat.I just want to calculate the total as shown above. Thanks in advance

This is pretty similar to Calculating sum of repeated elements in AngularJS ng-repeat this question. But not exactly. I am trying to calculate using expression since i have many rows

like image 425
Psyche Genie Avatar asked Nov 30 '22 01:11

Psyche Genie


1 Answers

It is possible to do it, but I think this kind of logic is best suited for your controller. Anyhow this is a possible way of achieving what you asked for using ng-init:

 <table ng-init="items.total = {}">
    <tr>
      <td>name</td>
      <td>numberofyears</td>
      <td>amount</td>
      <td>intrest</td>
    </tr>
    <tr ng-repeat="item in items">
      <td>{{item.name}}</td>
      <td ng-init="items.total.numberofyears = items.total.numberofyears + item.numberofyears">{{item.numberofyears}}</td>
      <td ng-init="items.total.amount = items.total.amount + item.amount">{{item.amount}}</td>
      <td ng-init="items.total.interest = items.total.interest + item.interest">{{item.interest}}%</td>
    </tr>
    <tr>
      <td>Total</td>
      <td>{{items.total.numberofyears}}</td>
      <td>{{items.total.amount}}</td>
      <td>{{items.total.interest}}%</td>
    </tr>
 </table>
like image 67
Wawy Avatar answered Dec 04 '22 10:12

Wawy