基于以下table我需要获取所有小计的总和。AngularJS:从多个对象中总结嵌套对象
我试图使用相同的sumByKey过滤器,但我没有工作。 另外,所有小计的总和必须基于过滤器的结果,这意味着,如果我们有两个结果(两个类别),则小计的总和必须基于这些对象。任何想法?
HTML
<table border="1">
<thead>
<tr>
<th>#</th>
<th>Category</th>
<th>Products with quantities</th>
<th>Subtotal of quantities</th>
</tr>
</thead>
<tbody align="center">
<tr data-ng-repeat="category in categories | filter:search">
<td>{{$index+1}}</td>
<td>{{category.name}}</td>
<td>{{category.products}}</td>
<td>{{category.products | sumByKey:'quantity'}}</td>
</tr>
</tbody>
<thead align="right">
<tr>
<td colspan="3"><strong>Total</strong></td>
<td></td>
</tr>
</thead>
</table>
angularjs
var app = angular.module("app", []);
app.controller("controllerApp", function($scope, $http){
$http.get("categories.json").success(function(data) {
$scope.categories = data;
});
});
app.filter('sumByKey', function() {
return function (data, key) {
if (typeof (data) === 'undefined' || typeof (key) === 'undefined') {
return 0;
}
var sum = 0;
for (var i = data.length - 1; i >= 0; i--) {
sum += parseInt(data[i][key]);
}
return sum;
}
});
当我过滤类别 '总' 必须根据经滤波的对象。尝试使用过滤器以查看总数。任何想法?顺便谢谢你的回答。 – wilson