在ng-repeat中总结ng-repeat

时间:2015-11-11 16:44:18

标签: javascript angularjs html-table

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

就像我有这种格式的信息一样:

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

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

2 个答案:

答案 0 :(得分:2)

假设数据结构如下:

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

答案 1 :(得分:1)

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

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

相关问题