[英]AngularJS. Filter array by array
我有這樣的數據結構:
$scope.data = [
{
title: "Title1",
countries: ['USA', 'Canada', 'Russia']
},
{
title: "Title2",
countries: ['France', 'Germany']
}
];
即每個項目都有國家名稱數組。
我正在顯示這樣的數據:
<tr ng-repeat="dataItem in data">
我希望允許用戶通過在輸入中提供國家/地區列表來過濾此列表:
如何做到這一點?
目前,我正在執行以下操作:
<input ng-model="searchFilter.countries">
...
<tr ng-repeat="dataItem in data | filter: searchFilter: true">
但是顯然,它僅適用於1個國家/地區,不適用於輸入中使用逗號列出的國家/地區。
沒有自定義過濾器的簡單解決方案:
HTML:
<input ng-model="countries" ng-list>
<tr ng-repeat="dataItem in data | filter:countryFilter">
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;
};
我在這里創建了一個示例。
它使用了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;
}
};
});
您的輸入只是一個字符串,而不是一個數組。 您可以為此目的使用ngList。
這是一個如何使用它的好例子: https : //docs.angularjs.org/api/ng/directive/ngList
searchFilter應該是您的$ scope上的方法。 否則默認情況下,它僅搜索字符串。
$scope.searchFilter = function (dataItem) {
//your search logic here and return true/false.
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.