AngularJS - How to structure a custom filter with ng-repeat to return items conditionally

删除回忆录丶 提交于 2019-11-26 11:19:16

Filters don't work on individual items in the array, they transform the entire array into another array.

userApp.filter('matchAccessLevel', function() {
  return function( items, userAccessLevel) {
    var filtered = [];
    angular.forEach(items, function(item) {
      if(userAccessLevel >= item.minAccess) {
        filtered.push(item);
      }
    });
    return filtered;
  };
});

See this plnkr

**always inspect the arguments to a function. It's not always obvious what the values are.*

see filters guide

You can use Array.filter for a more concise solution:

app.filter('matchAccessLevel', function() {
    return function( items, userAccessLevel ) {
      return items.filter(function(element){
        return userAccessLevel >= element.minAccess;
      });
    }
});

Check on Plunker

For CoffeeScript lovers:

userApp.filter 'matchAccessLevel', ->
  (items, userAccessLevel) ->
    item for item in items when userAccessLevel >= item.minAccess
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!