2016-11-21 50 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>