Dynamic filter within ng-repeat in AngularJS

╄→尐↘猪︶ㄣ 提交于 2019-12-05 10:30:19
DivZero

Apparently it is actually possible to pass arguments to your filter, but you have to make a custom filter instead of using "filter: expression". What I did was create a custom filter which takes the items and category as arguments and returns the array with filtered items.

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/  

I found a different and quite neat solution for sending parameters to the filter (written in es6):

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

the markup would be:

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

So basically you can just scope the "category" into the filter as myFilter returns a function on the format expected by the filter.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!