Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have data structure like this:

$scope.data = [
  {
    title: "Title1",
    countries: ['USA', 'Canada', 'Russia']
  },
  {
    title: "Title2",
    countries: ['France', 'Germany']
  }
];

I.e. 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:

enter image description here

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.

share|improve this question
    
It would be much easier if you create a JSFiddle –  Sreenath Nannat Jul 9 at 13:05

4 Answers 4

up vote 1 down vote accepted

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;
        }
    };
});
share|improve this answer

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

share|improve this answer

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

share|improve this answer

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.
};
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.