【问题标题】:How to calculate sum of rows in ng-repeat?如何计算 ng-repeat 中的行总和?
【发布时间】:2015-08-03 17:56:45
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案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;
        }
      })
      

      【讨论】:

      • 但我只需要那些在 ng-repeat 中按日期过滤的项目。
      • @curiousUser 你检查我的答案了吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      相关资源
      最近更新 更多