4

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.

1
  • Could you not pipe output of filter : dataFilter into another filter? Commented Nov 19, 2014 at 2:49

1 Answer 1

13

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.