我有一个稍微不同的要求,请您在标记为重复之前通读一遍。 举个例子:
<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 asresults
, 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/