[英]AngularJS. Filter array by array
I have data structure like this: 我有这样的数据结构:
$scope.data = [
{
title: "Title1",
countries: ['USA', 'Canada', 'Russia']
},
{
title: "Title2",
countries: ['France', 'Germany']
}
];
Ie each item has array of country names. 即每个项目都有国家名称数组。
I'm showing this data like this: 我正在显示这样的数据:
<tr ng-repeat="dataItem in data">
I want allow user to filter this list by providing list of countries in input: 我希望允许用户通过在输入中提供国家/地区列表来过滤此列表:
How to acheive this? 如何做到这一点?
Currently I'm did something like this: 目前,我正在执行以下操作:
<input ng-model="searchFilter.countries">
...
<tr ng-repeat="dataItem in data | filter: searchFilter: true">
But obviously it works only for 1 country, not for array of countries listed in input using comma. 但是显然,它仅适用于1个国家/地区,不适用于输入中使用逗号列出的国家/地区。
A simple solution, without a custom filter: 没有自定义过滤器的简单解决方案:
HTML: HTML:
<input ng-model="countries" ng-list>
<tr ng-repeat="dataItem in data | filter:countryFilter">
JS: JS:
$scope.countryFilter = function(dataItem) {
if (!$scope.countries || $scope.countries.length < 1)
return true;
var matched = false;
$scope.countries.filter(function(n) {
matched = matched || dataItem.countries.indexOf(n) != -1
});
return matched;
};
I have created an example here . 我在这里创建了一个示例。
It takes use of ngList
as Zahori recommended and defines a custom filter for countries. 它使用了
ngList
建议的ngList
,并为国家/地区定义了自定义过滤器。
myApp.filter('MyFilter', function() {
return function(items, countries) {
if (!angular.isUndefined(items) && !angular.isUndefined(countries) && countries.length > 0) {
var filtered = [];
angular.forEach(items, function(item) {
angular.forEach(countries, function(currentCountry) {
if(item.countries.indexOf(currentCountry) >= 0 ) filtered.push(item);
});
});
return filtered;
} else {
return items;
}
};
});
Your Input is just a String and not an Array. 您的输入只是一个字符串,而不是一个数组。 You can use ngList for this purpose.
您可以为此目的使用ngList。
Here is a good example how to use it: https://docs.angularjs.org/api/ng/directive/ngList 这是一个如何使用它的好例子: https : //docs.angularjs.org/api/ng/directive/ngList
searchFilter should be a method on your $scope. searchFilter应该是您的$ scope上的方法。 Otherwise by default it searches on string only.
否则默认情况下,它仅搜索字符串。
$scope.searchFilter = function (dataItem) {
//your search logic here and return true/false.
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.