gpt4 book ai didi

javascript - 如何计算ng-repeat中的行总和?

转载 作者:行者123 更新时间:2023-11-30 08:35:24 24 4
gpt4 key购买 nike

我有一个稍微不同的要求,请您在标记为重复之前通读一遍。举个例子:

<table ng:init="stuff={items:[{description:'gadget', cost:99,date:'jan3'},{description:'thing', cost:101,date:'july6'},{description:'thing', cost:101,date:'jan3'} ]}">
<tr>
<th>Description</th>
<th>Cost</th>
</tr>

<tr ng:repeat="item in stuff.items|filter"> /*only filtered item grouped by date*/
<td>{{item.description}}</td>
<td ng-bind='item.cost'>{{item.cost}}</td>
</tr>

<tr>
<td></td>
<td>{{total}}</td> /*cost of items grouped by date jan3*/
</tr>
</table>

我如何计算按项目分组的总成本?是否 Angular 任何数据属性,我可以在其中添加分组项目的成本,然后再次为下一个分组项目重新初始化它?

最佳答案

Angular 1.3 添加了 create an alias to your ng-repeat 的能力,这在与过滤器结合使用时非常有用。

variable in expression as alias_expression – You can also provide an optional alias expression which will then store the intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message when a filter is active on the repeater, but the filtered result set is empty.

For example: item in items | filter:x as results will store the fragment of the repeated items as results, but only after the items have been processed through the filter.

因此,您可以使用此 as alias_expression 对列表的过滤子集执行计算。即:

<tr ng-repeat="item in stuff.items|filter as filteredStuff">
{{filteredStuff.length}}
{{calculateTotal(filteredStuff)}}
</tr>

在 Controller 中:

$scope.calculateTotal = function(filteredArray){
var total = 0;
angular.forEach(filteredArray, function(item){
total += item.cost;
});
return total;
};

关于javascript - 如何计算ng-repeat中的行总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31793727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com