有没有办法创建一个返回对象的custom angular filter function?
我从文档中了解到过滤器:可以将对象作为表达式。例如,以下仅包含名为Neil Diamond的对象:
<div ng-repeat="item in collection | filter:{'name':'Neil Diamond'}">
我试图过滤动态对象。我创建了一个构建对象并返回它的函数,但这并不起作用。这是实现我的目标的一种不合适的方法吗?
<input type="checkbox" ng-click="includeAudience('Clinicians')" /> Clinicians
<br>
<input type="checkbox" ng-click="includeAudience('ElderlyVeterans')" /> ElderlyVeterans
<ul>
<li ng-repeat="resource in resources | filter:audienceFilter">
{{resource.name}}
</li>
</ul>
$scope.resources = [{
'name': 'Resource 1',
'ElderlyVeterans': false,
'Clinicians': true
}, {
'name': 'Resource 2',
'ElderlyVeterans': true,
'Clinicians': false
}];
$scope.audienceIncludes = [];
$scope.includeAudience = function(resource) {
var i = $.inArray(colour, $scope.audienceIncludes);
if (i > -1) {
$scope.audienceIncludes.splice(i, 1);
} else {
$scope.audienceIncludes.push(resource);
}
}
$scope.audienceFilter = function(resource) {
if ($scope.audienceIncludes.length > 0) {
$scope.audiencesShown = {};
angular.forEach($scope.audienceIncludes, function(audience) {
$scope.audiencesShown[audience] = true;
});
return $scope.audiencesShown;
}
return resource;
}
});
你可以在这里看到JSFiddle:http://jsfiddle.net/matthew_nahmias/5oqda19n/
答案 0 :(得分:0)
这是因为您将该功能作为原始对象。这意味着angular会将函数本身视为过滤器,而不是它的结果。您应该评估该功能,如下所示:
<li ng-repeat="resource in resources | filter:audienceFilter()">
{{resource.name}}
</li>
(我在audienceFilter
之后添加了括号。)
这似乎至少在jsfiddle中起作用。