AngularJS:如何从multilpe数组中求和相似的变量

时间:2016-11-21 01:23:38

标签: angularjs

请在这个问题的最后看看我需要做些什么。

我在类别和产品之间有以下关系(1-n)。

enter image description here

这是带库存的html表

<table>
<thead>
    <tr>
        <th>#</th>
        <th>Category</th>
        <th>Products quantity</th>
    </tr>   
</thead>
<tbody>
    <tr data-ng-repeat="category in categories" data-ng-repeat="getProductsByCategory(category)">
        <td>{{category.name}}</td>
        <td>{{products[category.id] | sumByKey:'quantity'}}</td>
    </tr>
</tbody>
<tfooter>
    <tr>
        <td colspan="2">total</td>
        <td></td>
    </tr>
</footer>   

这就是结果,因为你可以看到我正在使用'sumByKey'过滤器,以便按类别获得所有产品的总和

enter image description here

按类别获取所有产品的相应功能

$scope.products = [];
$scope.getProductsByCategory = function(category){
    $http.get("getProductsByCategory/"+category.id)
    .success(function (data, status, headers, config) {
        $scope.products[category.id] = data;
    })
    .error(function (data, status, header, config) {
        $log.error("Error");
    });
};

过滤器总和所有数量

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

为了获得库存表中的总数,我一直在尝试使用相同的过滤器( sumByKey ),但它不起作用。有想法得到相应的结果吗?

2 个答案:

答案 0 :(得分:2)

您可以做的是调用控制器中的过滤器并将结果添加到总数中。

$scope.total = 0;

$scope.sum = function(value) {
    var results = // sum returned by your filter;

    // maintains count of all category sums
    $scope.total += results;

    // amount that goes back to the view
    return results; 
}

然后将$ scope.total绑定到您的视图。

<td>{{products[category.id] | sum('quantity')}}</td>

答案 1 :(得分:0)

似乎$ scope.products将是[ProductArrayCat1,ProductArrayCat2,ProductArrayCat3]

所以你要做的就是将3个数组分别抛给sumByKey过滤器。

<tfooter>
<tr>
    <td colspan="2">total</td>
    <td>{{total}}</td>
</tr>

$scope.total=0;
$scope.getProductsByCategory $scope.getProductsByCategory= function(category){
$http.get("getProductsByCategory/"+category.id)
.success(function (data, status, headers, config) {
    $scope.products[category.id] = data;
    $scope.total += $filter('sumByKey')(data,'quantity');
});
};