我有一个对象:
$scope.basketList = [{id : A1, name : metal},
{id : A2, name : plastic},
{id : B1, name : fiber}];
$scope.itemList = [{ id : 1, basket_id : 'A1', ctg : 'fruit', stok : 3},
{ id : 2, basket_id : 'A2', ctg : 'fruit', stock : 2},
{ id : 4, basket_id : 'A1', ctg : 'fruit', stock : 4},
{ id : 5, basket_id : 'B1', ctg : 'fruit', stock : 1},
{ id : 6, basket_id : 'B1', ctg : 'fruit', stock : 2},
{ id : 7, basket_id : 'A1', ctg : 'fruit', stock : 4},
{ id : 8, basket_id : 'A2', ctg : 'fruit', stock : 2}];
在HTML中:
<div class="stock">
<div ng-repeat="basket in $scope.basketList>
<div>Basket : {{basket.name}}</div>
<div ng-repeat="item in itemList | filter : {basket_id : basket.id}"></div>
</div>
</div>
如何过滤和总和库存。 所以,输出将是这样的:
金属
friut,stock = 11
塑料
fruit,stock = 4
纤维
fruit,stock = 3
答案 0 :(得分:0)
对于一个简单的答案,您可以创建函数来计算总库存值和“ctg”。例如
$scope.getTotal = function(basket) {
var totalStock = $scope.itemList.reduce(function(total, curr){
if (curr.basket_id === basket.id) return total + curr.stock;
return total;
}, 0);
return totalStock;
}
$scope.getCtg = function(basket) {
for (var i = 0; i < $scope.itemList.length; i++) {
if (basket.id === $scope.itemList[i].basket_id) return $scope.itemList[i].ctg;
}
return 'not found';
}
您需要调整模板:
<div class="stock">
<div ng-repeat="basket in basketList">
<div>Basket : {{basket.name}}</div>
<span ng-bind="getCtg(basket)"></span>,
<span ng-bind="getTotal(basket)"></span>
</div>
这是一个完整的jsfiddle:http://jsfiddle.net/2c3pmhpa/4/
当然,在实际应用中,您可能会制作更通用的解决方案,但这应该适用于您的简单案例。