...">

Dynamic filter in ng repeat in AngularJS

For my AngularJS application, I have ng-repeat in ng-repeat, for example:

Html:

<div ng-app="myApp"> <div ng-controller="myController"> <h2>working filter</h2> <div ng-repeat="category in categories"> <h3>{{category}}</h3> <div ng-repeat="item in items | filter:{price.red: 0} ">{{item.name}}</div> </div> <h2>broken filter</h2> <div ng-repeat="category in categories"> <h3>{{category}}</h3> <!-- price[category] should be red, blue, yellow, depending on the category in the ng-repeat --> <!-- price[category] should be bigger then 0 (or not zero, negative values will not occur) --> <div ng-repeat="item in items | filter:{price[category]: 0} ">{{item.name}}</div> </div> </div> </div> 

JavaScript:

 var myApp = angular.module('myApp', []); myApp.controller('myController', function ($scope) { $scope.categories = ['red', 'blue', 'yellow']; $scope.items = [ {name: 'one', price:{red: 0, blue: 1, yellow: 3} }, {name: 'two', price:{red: 2, blue: 0, yellow: 0}}, ] }); 

Check out my jsFiddle http://jsfiddle.net/hm8qD/

So, I ran into two problems:

  • Flter does not accept [] brackets, so I cannot make the filter dynamic based on the category
  • The filter must return items whose price [category] is greater than zero.

For a larger zero, I could just create my own filter. However, as far as I know, filters do not accept parameters, so I canโ€™t get the category (red, blue or yellow).

Please note that this is a simplified version of my actual code, and this context may not make much sense. Hopefully I realized that I need a filter because I'm new to AngularJS.

+4
source share
2 answers

Apparently, it is actually possible to pass arguments to your filter, but you should create your own filter instead of using "filter: expression". What I did was create a custom filter that takes elements and a category as arguments and returns an array with filtered elements.

 myApp.filter('myFilter', function () { return function (items, category) { var newItems = []; for (var i = 0; i < items.length; i++) { if (items[i].price[category] > 0) { newItems.push(items[i]); } }; return newItems; } }); 

See the updated Fiddle here: http://jsfiddle.net/hm8qD/3/

+2
source

I found another and rather neat solution for sending parameters to a filter (written in es6):

 $scope.myFilter = (category) => { return (item) => { if(category === 'fish' && item.type === 'salmon'){ return true } return false } } 

markup will be:

 <div ng-repeat="item in items | filter:myFilter(someCategory)> {{item.name}} </div> 

That way, you can simply include the โ€œcategoryโ€ in the filter, since myFilter returns the function in the format expected by the filter.

0
source

Source: https://habr.com/ru/post/1481376/


All Articles