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

时间:2015-08-03 17:56:45

标签: javascript angularjs angularjs-ng-repeat ng-repeat angularjs-filter

我的要求略有不同,请您在标记为重复之前请仔细阅读。 举个例子:

<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>

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

2 个答案:

答案 0 :(得分:3)

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

  

variable in expression as alias_expression - 您还可以提供一个可选的别名表达式,然后在应用过滤器后存储转发器的中间结果。通常,这用于在转发器上的筛选器处于活动状态时呈现特殊消息,但筛选结果集为空。

     

例如:item in items | filter:x as results会将重复项的片段存储为results,但只有在通过过滤器处理完项目后才会存储。

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

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

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

答案 1 :(得分:2)

您可以创建自己的自定义过滤器,接受该数组将返回所有项目的总费用。

<强>标记

<tr ng:repeat="item in filteredData = (stuff.items|filter)">
    <td>{{item.description}}</td>
    <td ng-bind='item.cost'>{{item.cost}}</td>
</tr>
<tr>
    <td></td>
    <td>{{filteredData| total}}</td>   /*cost of items grouped by date jan3*/
</tr>

<强>代码

app.filter('total', function(){
  return function(array){
    var total = 0;
    angular.forEach(array, function(value, index){
       if(!isNaN(value.cost))
        total = total + parseFloat(value.cost);
    })
    return total;
  }
})
相关问题