【问题标题】:Summing an ng-repeat inside an ng-repeat在 ng-repeat 中求和 ng-repeat
【发布时间】:2017-06-19 02:50:06
【问题描述】:

有没有办法让我总结一个内部循环:

如果我有这种格式的信息:

 a : {b:[1,2,3,4,5]}

现在我这样迭代:

<tr ng-repeat="group in whole">
    <td>{{group.name}}</td>
    <td ng-repeat="list in group">
         {{element.amt}}
    </td>
</tr>

我想在每列的末尾得到一个总数。

到目前为止我有这个解决方案:

$scope.$watch('data', function(newValue) {
    if (newValue !== undefined) {
        angular.forEach(newValue, function(val, key) {
            $scope.allSum=0;
            angular.forEach(val.list, function(v, k) {
                v.sum = v.value;
            });
        });
     }
}, true);

所以我能够计算每一行的值,但是变量只映射到显示的最后一行。

【问题讨论】:

  • 只需将总数显示为$scope 函数调用,如{{getSum(group)}}。它将使用数据正确更新。

标签: javascript angularjs html-table


【解决方案1】:

假设数据结构如下:

{
    a : { b : [1,2,3,4,5] },
    c : { d : [6,7,8,9,10] },
    e : { f : [11,12,13,14,15] }
}

在模板中:

        <tr>
            <td>Total: </td>
            <td>{{ getTotal() }}</td>
        </tr>

在控制器中:

$scope.getTotal = function getTotal() {
    var total = 0, sum = 0;
    // iterate through the whole group -- "a,c,e" keys
    for (var obj in $scope.group) {
        // grab current element's array -- first key of the current object
        var arr = Object.keys(obj)[0];
        // utilize reduce to sum all values in array
        sum = arr.reduce(function(a,b) { return a + b; }, 0);
        // increment total
        total += sum;
    }
    return total
};

【讨论】:

    【解决方案2】:

    你可以编写简单的过滤器:

    app.filter('sum', function() {
      return function(array, property) {
        var result = 0;
        for (var i = 0; i < array.length; i++) {
          result += (property ? array[i][property] : array[i]);
        }
    
        return result;
      }
    })
    

    http://plnkr.co/edit/VVm2r1WgTnDvqhw2ub3Q?p=preview

    【讨论】:

      猜你喜欢
      • 2017-12-22
      • 2013-11-23
      • 1970-01-01
      • 2013-08-11
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多