infomofo infomofo - 1 month ago 7
AngularJS Question

Is it possible to filter angular.js by containment in another array?

So if I have an array:

$scope.letters =
[{"id":"a"},
{"id":"b"},
{"id":"c"}];


And another array

$scope.filterBy = ["b","c","d"];


And I want to have some ng-repeat to filter $scope.letters by only items that appear in $filterBy.

I want to be able to do something to the effect of:

<span ng-repeat="{{letter in letters|filter: letter.id in filterBy }} > {{letter.id}} </span>


And have it print b,c

I know this is a really stupid example, but is there a way to filter an angular.js expression based on the contents of another array object?

Answer

You should try something like that:

JS:

angular.module('Test', []);

function Ctrl($scope) {
  $scope.letters = [
    {id: 'a'},
    {id: 'b'},
    {id: 'c'}
  ];

  $scope.filterBy = ['b', 'c', 'd'];

  $scope.filteredLetters = function () {
    return $scope.letters.filter(function (letter) {
      return $scope.filterBy.indexOf(letter.id) !== -1;
    });
  };
}

Ctrl.$inject = ['$scope'];

HTML:

<div ng-repeat='letter in filteredLetters(letters)'>{{letter.id}}</div>

You can try live example.

Comments