2

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.

1
  • It would be much easier if you create a JSFiddle Commented Jul 9, 2014 at 13:05

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.