I
I
Ivan Feofanov2015-08-06 15:37:45
Angular
Ivan Feofanov, 2015-08-06 15:37:45

How to create a custom filter with dependencies in AngularJS?

Good afternoon.
I've been struggling with a problem for several hours, the cause of which, most likely, is my poor knowledge of AngularJS. As they say, I googled all my fingers into the blood, but did not find a solution.
It is necessary to create a custom filter that would reject everything that is included in the given array. The array is available in $scope, the filter is in a separate file addIngrFilter.js
Here is the code of the file with the filter:

angular
  .module('quApp')
  .filter('addIngrFilter', ['$scope', function($scope) {
    return function (items){
      var filtered = [];
      items.forEach(function(item){
        if($scope.dishIngredientsIndexes.indexOf(item.id)<0){
          filtered.push(item);
        }
      });
      return filtered;
    };
  }]);

However, Angular complains, says Error: [$injector:unpr] and sends it to: https://docs.angularjs.org/error/$injector/unpr?p0...
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Feofanov, 2015-08-07
@Papazian

I decided! The final filter code looks like this:

angular
  .module('quApp')
  .filter('ingrListFilter', function() {
    return function (items, filter){
      return _.reject(items, function(item){
        return _.contains(filter, item.id);
      });
    };
  });

And the filter call is like this:
<span ng-repeat="ingredient in ingredients | ingrListFilter:dishIngredientsIndexes">
    <span class="badge">{{ingredient.name}}</span>
</span>

dishIngredientIndexes is an array to filter the input data.

P
Pavel Kononenko, 2015-08-06
@premas

$scope is only available inside controllers and link functions of directives. And the filter should not be rigidly tied to some variable. You must pass it to the filter. If I understand correctly, then you need to:

.filter('addIngrFilter', [function() {
    return function (items, item){
      var filtered = [];
      items.forEach(function(items){
        if(items.indexOf(item.id)<0){
          filtered.push(item);
        }
      });
      return filtered;
    };
  }]);

In general, get acquainted with Underscore.js

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question