Sunil
Sunil

Reputation: 127

Getting the sum of number of quantity in angularjs

I am using angularjs to list, filter and sort my items list.i was able group and filter, but could not get the sum of the qty of the individual food item. i could not get the number of items inside the group item and could not get the sum of qty of the grouped item. my fiddle

Output I got

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

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

Output i need

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>

Controller

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;
    }
}

Upvotes: 0

Views: 358

Answers (1)

kubuntu
kubuntu

Reputation: 2535

list.name.length*1 in your HTML simply counts characters in name adds qty to it. You can modify HTML as follows using groupBy (requires angular-filter as pointed out by @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>

Then add function to get sum in controller

$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;
}

It seems like angular-filter requires an Angular version above 1.1.1 which was in your Fiddle.

Here is modified Fiddle - http://jsfiddle.net/ranru/gmLjtxub/1/

Upvotes: 1

Related Questions