只是为了好玩,我实现了一个具有更简单 API 的解决方案(希望在评论中提供线索)。它是这样的:
给控制器添加cbFilter
依赖,去掉所有checkbox
相关代码,替换如下;这是新的 API(再简单不过了 :)
app.controller('resultsData', function($scope, $http, cbFilter){
...
$scope.checkbox = cbFilter($scope, "provider.providerId");
...
}
R替换列表中的过滤器(注意searchByCheckbox
替换为checkbox
):
<li data-ng-repeat="result in ( filteredItems = (results | filter: searchByCarClass | filter: selectCarClass | filter: checkbox )) | orderBy:orderByFilter">
最后,添加服务:
app.factory("cbFilter", ["$parse", function($parse) {
return function($scope, matchExpression) {
var showAll = true,
getter = $parse(matchExpression),
filter = function(data) {
if( showAll ) return true;
return filter[getter(data)] === true;
},
unwatch = $scope.$watch(
function() {
var x, ret = {};
for( x in filter ) {
if( !filter.hasOwnProperty(x) ) continue;
ret[x] = filter[x];
}
return ret;
},
function() {
showAll = true;
angular.forEach(filter, function(val) {
if( val === true ) showAll = false;
});
},
true
);
$scope.$on("$destroy", unwatch);
return filter;
};
}]);
实现比以前复杂得多,而且可能更慢。然而,API 要简单得多(单行)。