简体   繁体   中英

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.

A simple solution, without a custom filter:

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;
};

DEMO PLUNKR

I have created an example here .

It takes use of ngList as Zahori recommended and defines a custom filter for countries.

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.

Here is a good example how to use it: https://docs.angularjs.org/api/ng/directive/ngList

searchFilter should be a method on your $scope. Otherwise by default it searches on string only.

$scope.searchFilter = function (dataItem) {
    //your search logic here and return true/false.
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM