Answer the question
In order to leave comments, you need to log in
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;
};
}]);
Answer the question
In order to leave comments, you need to log in
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);
});
};
});
<span ng-repeat="ingredient in ingredients | ingrListFilter:dishIngredientsIndexes">
<span class="badge">{{ingredient.name}}</span>
</span>
$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;
};
}]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question