获得angularjs中数量的总和

时间:2016-02-22 13:58:48

标签: angularjs filter

我正在使用angularjs列出,过滤和排序我的项目列表。我能够进行组和过滤,但无法获得单个食物项目的数量之和。我无法获得组项目中的项目数量,也无法获得分组项目的数量之和。我的fiddle

我得到的输出

Paneer Tikka - 13
Name: Paneer Tikka- PRICE: 125 - QTY: 1

Falooda - 9
Name: Falooda- PRICE: 85 - QTY: 2
Name: Falooda- PRICE: 85 - QTY: 1

我需要输出

Paneer Tikka - 1
Name: Paneer Tikka- PRICE: 125 - QTY: 1

Falooda - 3
Name: Falooda- PRICE: 85 - QTY: 2
Name: Falooda- PRICE: 85 - QTY: 1

HTML

<div ng-app ng-controller="Main">
<div ng-repeat="list in itemsToFilter() | filter:filterNames">
    <b>{{list.name}} - {{(list.name.length*1)+(list.qty*1)}}</b>
    <li ng-repeat="item in itemsToFilter() | filter: {name: list.name}">NAME: {{item.name}}- PRICE: {{item.price}} - QTY: {{item.qty}}</li>        
</div>
</div>

控制器

function Main($scope) {
$scope.list = {
"_id": "56c4758af801160e00d176e0",
"orderfood": [
{
"_id": "569d84f04834c10e003dff36",
"qty": "1",
"confirm": "placed",
"price": 125,
"name": "Paneer Tikka"
},
{
"_id": "569d869fff1fe20e00f8ba9b",
"qty": "2",
"confirm": "placed",
"price": 85,
"name": "Falooda"
},
{
"_id": "569d869fff1fe20e00f8ba9b",
"qty": "1",
"confirm": "placed",
"price": 85,
"name": "Falooda"
}
],
"title": "Status",
"created": "2016-02-17T13:28:42.226Z"
}

    var indexedTeams = [];

    $scope.itemsToFilter = function() {
        indexedTeams = [];
        return $scope.list.orderfood;
    }

    $scope.filterNames = function(item) {
        var nameIsNew = indexedTeams.indexOf(item.name) == -1;
        if (nameIsNew) {
            indexedTeams.push(item.name);
        }

        return nameIsNew;
    }
}

1 个答案:

答案 0 :(得分:1)

HTML中的

list.name.length*1只会计算name中添加qty字符的字符数。您可以使用groupBy按照以下方式修改HTML(需要angular-filter,如@andreiho所指出的那样。)

<div ng-app ng-controller="Main">
<div ng-repeat="(key,value) in itemsToFilter() | groupBy: 'name'">
    <b>{{ key }} - {{ getSum(value) }}</b>
    <li ng-repeat="item in value">NAME: {{ item.name }}- PRICE: {{ item.price }} - QTY: {{ item.qty }}</li>        
</div>
</div>

然后添加函数以在控制器中获得总和

$scope.getSum = function(val) {
  var sum = 0;
  for (var i = 0; i < val.length; i++) { // iterate and get sum
    sum += parseInt(val[i].qty);
  }
  return sum;
}

似乎angular-filter需要1.1 {1}以上的Angular版本。

此处经过修改Fiddle - Fiddle