calculate the sum of values in ng repeat Angularjs

廉价感情. 提交于 2019-11-30 07:55:36

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>

As the comments mention - you would sum in your controller and display the summed value after your ng-repeat.

https://docs.angularjs.org/api/ng/directive/ngRepeat

The ngRepeat directive instantiates a template once per item from a collection.

So, ng-repeat is for rendering and would not be the place for business logic.

Do the Math in controller, then you can add <tr ng-if="$last"> </tr> In ng-repeat and show the final result

controller e.x - simple one

function sum (object) {
    var data = object;
    var tmpSum

     for (var i in object){
      tmpSum =+ object[i].value;
    }

    $scope.sum = tmpSum 
};

view e.x

<tr ng-if="$last">{{sum}} </tr>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!