Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
AngularJS:如何对多LPE数组中的相似变量求和_Angularjs - Fatal编程技术网

AngularJS:如何对多LPE数组中的相似变量求和

AngularJS:如何对多LPE数组中的相似变量求和,angularjs,Angularjs,请看我在这个问题的结尾需要做什么 我在类别和产品之间有以下关系(1-n) 这是包含清单的html表 <table> <thead> <tr> <th>#</th> <th>Category</th> <th>Products quantity</th> </tr> </thead> <tb

请看我在这个问题的结尾需要做什么

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

这是包含清单的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>   
并使用过滤器对所有数量求和

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),但它不起作用。想要得到相应的结果吗?

您可以在控制器中调用过滤器,并将结果添加到总数中

$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>
{{products[category.id]| sum('quantity')}

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

因此,您所要做的就是将3个数组分别抛出到sumByKey过滤器

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

由于您正在进行Api调用,我强烈建议您在数据库、存储过程调用或视图中执行此操作。然后,您可以将其作为响应数据的一部分这可以帮助你
<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');
});
};