2016-11-21 54 views
1

请看我在这个问题的最后需要做些什么。AngularJS:如何从多字节数组中总结类似变量

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

enter image description here

这与库存

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

的HTML表,这就是结果,你可以看到我使用'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)但它不起作用。任何想法得到相应的结果?

+1

因为它似乎你正在做的API调用,我会_highly_建议在数据库中这样做,在你的存储过程调用或视图。然后,您可以将其作为响应数据的一部分。 – Yatrix

+1

http://stackoverflow.com/a/40697761/3279156 -----这可以帮助你 – sreeramu

回答

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