Angular 按包含搜索条件的数组过滤
Angular filter by array that contains search criteria
内置 Angular "filter" 是否支持过滤数组 "filter where array contains "
例如:
$scope.currentFilter = "Allentown";
$scope.users = [{
name: "user1",
locations: [
{ name: "New York", ... },
{ name: "Allentown", ... },
{ name: "Anderson", ... },
]
}, ... ];
<div ng-repeat="user in users | filter : { locations: { name: currentFilter } }"></div>
换句话说,我希望仅过滤到具有 "locations" 数组且包含按名称匹配字符串的位置的用户。
如果没有,我如何使用自定义过滤器完成此操作?
您的代码片段按原样工作,因为 Angular 1.2.13. In case you're using an older version (tested on 1.0.1) and don't need to reuse your filtering routine across controllers (in which case you should declare a proper filter), you can pass the built-in filter 一个谓词函数 :
<div ng-repeat="user in users | filter : hasLocation">{{user.name}}</div>
然后这样写:
$scope.currentFilter = "Allentown";
$scope.hasLocation = function(value, index, array) {
return value.locations.some(function(location) {
return location.name == $scope.currentFilter;
});
}
Fiddle here.
内置 Angular "filter" 是否支持过滤数组 "filter where array contains "
例如:
$scope.currentFilter = "Allentown";
$scope.users = [{
name: "user1",
locations: [
{ name: "New York", ... },
{ name: "Allentown", ... },
{ name: "Anderson", ... },
]
}, ... ];
<div ng-repeat="user in users | filter : { locations: { name: currentFilter } }"></div>
换句话说,我希望仅过滤到具有 "locations" 数组且包含按名称匹配字符串的位置的用户。
如果没有,我如何使用自定义过滤器完成此操作?
您的代码片段按原样工作,因为 Angular 1.2.13. In case you're using an older version (tested on 1.0.1) and don't need to reuse your filtering routine across controllers (in which case you should declare a proper filter), you can pass the built-in filter 一个谓词函数 :
<div ng-repeat="user in users | filter : hasLocation">{{user.name}}</div>
然后这样写:
$scope.currentFilter = "Allentown";
$scope.hasLocation = function(value, index, array) {
return value.locations.some(function(location) {
return location.name == $scope.currentFilter;
});
}
Fiddle here.