Search code examples
angularjsangular-filters

How to pass $scope value to custom filter in AngularJs?


I have an array show below,

$scope.selectionCat = ['1','3','4']

In HTML am calling like

<div dir-paginate="item in items | filterForCat:this">

Custom filter

.filter('filterForCat', function () {
  return function (item, scope) {
    return (scope.selectionCat.indexOf(item.category_id.id) !== -1);
  };
})

When am trying to read'scope.selectionCat' values am getting error like 'Cannot read property 'id' of undefined'

Can i get any help to solve this?


Solution

  • Guess you want to filter items which's id is included by scope.selectionCat, as commented by @JB Nizet, you should not pass scope(this) to filters which you can but should avoid using filter this way, and you have to return filter result not just true/false of an expression.

    Also for the error you are facing will be solved by Array.filter for if there's no data in items, the callback of Array.filter won't be executed.

    Here you filter can be written like below

    .filter('filterForCat', function () {
      return function (items, selectionVat) {
        return items.filter(function(item) {
          return selectionCat.indexOf(item.category_id.id) !== -1
        });
      };
    })