计算 ng repeat Angularjs 中的值的总和 [英] calculate the sum of values in ng repeat Angularjs
问题描述
我是 Angularjs 的新手.我正在使用 ng-repeat 显示项目列表.如何计算它的总和?有没有什么简单的方法可以使用表达式在html中计算它?
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%
前三行来自 ng repeat.我只想计算如上所示的总数.提前致谢
First three rows are from ng repeat.I just want to calculate the total as shown above. Thanks in advance
这非常类似于 计算中重复元素的总和AngularJS ng-repeat 这个问题.但不完全是.我正在尝试使用表达式进行计算,因为我有很多行
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
推荐答案
这样做是可能的,但我认为这种逻辑最适合您的控制器.无论如何,这是使用 ng-init 实现您所要求的一种可能方式:
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>
这篇关于计算 ng repeat Angularjs 中的值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!