Search code examples
javascriptangularjsangular-filters

Angular JS filter 2 values?


I have a filter:

angular.module('pb.ds.foundation').filter('notAvailable', function () {
  return function (items, name) {
    var arrayToReturn = [];

    for (var i = 0; i < items.length; i++) {
      if (items[i].code !== name) {
        arrayToReturn.push(items[i]);
      }
    }

    return arrayToReturn;
  };
});

which I wrote to filter out a given item from an ng-repeat:

ng-repeat="nio in icons.nucleoIcons | notAvailable: 'arrows-2_time'"

Now, however, I'd like to filter a second icon (string) from my repeater. Do I need to pipe the same filter a second time with the new value, or is there a way to pass the filter 1 or more values?


Solution

  • There are couple of ways you can accomplish this. You can pass a string to the filter, as you did, but you can also pass an array or a scope variable as well.

    Here is a plnk that has the filter updated to accept a string, array, or scope variable.

    angular.module('app', [])
    .filter('notAvailable', function () {
      return function (items, name) {
        var arrayToReturn = [];
    
        if (Array.isArray(name)) {
          for (var i = 0; i < items.length; i++) {
            if (name.indexOf(items[i].code) === -1) {
              arrayToReturn.push(items[i]);
            }
          }
        } else {
          for (var i = 0; i < items.length; i++) {
            if (items[i].code !== name) {
              arrayToReturn.push(items[i]);
            }
          }
        }
    
        return arrayToReturn;
      };
    })