您可以在绑定数据时在视图模型本身中设置该计数,或者在作用域上只有一个返回计数的方法。
app.controller('MainController', function($scope, filterFilter){ .... $scope.getCount = function(strCat){ return filterFilter( $scope.heroes, {comic:strCat}).length; } ...});并将其用作:-
Marvel [{{getCount("Marvel")}}] ..... DC Comics [{{getCount("DC")}}]普伦克
如果您在页面上时列表不变,我建议您找出长度并将其绑定到视图模型本身的属性中,然后在视图中使用它。
//Set your data model $scope.cbMarvel = {value:true, count:getCount('Marvel')}; $scope.cbDCComics = {value:true, count:getCount('DC')};在你看来
<input type="checkbox" ng-model="cbMarvel.value"/> Marvel [{{cbMarvel.count}}]Plnkr2
如果您的数据集很大,请使用forEach并立即填充每种类型的计数,而不是在getCount中使用过滤器。
实际上,您根本不需要过滤器,在这种情况下,使用过滤器遍历同一列表似乎效率很低。您的列表是静态列表,因此请在控制器本身中对其进行分类。
var comics = $scope.comics = {}; //Dictionary of comics //Create the collection here. angular.forEach(heroes, function(itm){ if(!comics[itm.comic]){ comics[itm.comic] = {name:itm.comic, value:true, count:1, items:[itm] }; return; } comics[itm.comic].count++; //Incr count comics[itm.comic].items.push(itm); //push specific item });并删除您视图中的所有过滤器,然后执行以下操作:
<div ng-repeat="h in comics.Marvel.items" ng-show="comics.Marvel.value"> {{ h.name}} - {{h.comic}} </div> <div ng-repeat="h in comics.DC.items" ng-show="comics.DC.value"> {{ h.name}} - {{h.comic}} </div>Plnk3-更好的一个



