javascript - AngularJS filter and summary -
i have object :
$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}];
in 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>
how filter , sum stock. so, output :
metal
friut, stock = 11
plastic
fruit, stock = 4
fiber
fruit, stock = 3
for simple answer create functions calculate total stock value , "ctg". example
$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) { (var = 0; < $scope.itemlist.length; i++) { if (basket.id === $scope.itemlist[i].basket_id) return $scope.itemlist[i].ctg; } return 'not found'; }
you need adjust template:
<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>
here's complete jsfiddle: http://jsfiddle.net/2c3pmhpa/4/
of course in real application make more generic solution should work simple case.