Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate sum of rows in ng-repeat with existing filter

Tags:

angularjs

I have simple filter like this:

 <div id="dataFilter">
     <input type="search" ng-model="dataFilter" />
 </div>

And ng-repeat:

 <tr class="row"
    ng-repeat="obj in allObjects
    | filter: dataFilter
    | orderBy:orderProperty:orderReverse" >
    <td>
        {{obj.value}}
    </td>
</tr>

How can I do some calculations with alredy filtred objects?
I mean... I need do some stuff with obj.Value s but only for filtred objects.

like image 555
Maksim Nesterenko Avatar asked Dec 14 '22 18:12

Maksim Nesterenko


1 Answers

If you save a reference to the filtered list then it can be used to calculate the sum:

View:

<p ng-repeat="city in (filteredList = (cities | filter: dataFilter))"></p>

<p>Total population: {{calculateTotal(filteredList)}}</p>

Controller:

$scope.calculateTotal = function(cities){
   // calculate total
}

angular.module('MyModule', [])

.controller('MyController', function($scope) {

  $scope.cities = [
    { id: 1, name: 'Moscow', population: 11.84},
    { id: 2, name: 'St Petersburg', population: 5.03},
    { id: 3, name: 'Novosibirsk', population: 1.52},
    { id: 4, name: 'Jekateriburg', population: 1.4},
    { id: 5, name: 'Novogorod', population: 1.26}
  ];

  $scope.calculateTotal = function(cities){
    return cities.reduce( function(totalPopulation, city){
      return totalPopulation + city.population
    }, 0);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='MyModule' ng-controller='MyController'>
  
  <input type="search" ng-model="dataFilter"/>

  <p ng-repeat="city in (filteredList = (cities | filter: dataFilter))">{{city.name}}, population: {{city.population}}</p>

  <p>Total poulation: {{calculateTotal(filteredList)}}</p>
</div>
like image 152
Gruff Bunny Avatar answered Feb 12 '23 10:02

Gruff Bunny