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

标签 javascript angularjs angularjs-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>

我如何计算按项目分组的总成本?是否 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/

相关文章:

javascript - 网页未调整大小 - 代码中没有约束

javascript - 将元素移到左侧 javascript/css

javascript - $http.post 的 angularjs 服务未输入成功或错误回调

angularjs - 如何配置 Nginx 以使用 html5 模式

javascript - 将焦点添加到添加的每个新文本输入上

javascript - 为什么我的 https 来源没有使用 navigator Geolocation 服务的权限?

angularjs - UI Bootstrap template-url 是否支持常见的 Angular 表达式

jquery - 无法让日期选择器与 ng-repeat 一起使用

javascript - Angularjs ng-repeat 在另一个 ng-repeat 中

javascript - AngularJS 重复但根据条件删除嵌套部分