如何使用现有过滤器计算ng-repeat中的行总和

时间:2014-11-19 02:36:49

标签: angularjs

我有这样的简单过滤器:

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

并且ng-repeat:

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

如何使用alredy filtred对象进行一些计算?
我的意思是......我需要用obj.Value来做一些事情,但仅限于过滤对象。

1 个答案:

答案 0 :(得分:11)

如果保存对已过滤列表的引用,则可以使用它来计算总和:

查看:

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

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

控制器:

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