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

AngularjsNg RepeatAngular Filters

Angularjs Problem Overview


I have an ng-repeat that prints list items. I want to write a custom filter so that the list item will print, only if a condition is true.

I seem to have the structure wrong as it seems the variables are not getting passed through to the filter.

index.php

<div ng-show="userDetails.username" class="nav">
    <p>Menu</p>
    <li ng-repeat="menuItem in menu | matchAccessLevel:$rootScope.userDetails.accessLevel:menuItem.minAccess | orderBy:'position' ">
        <a ng-href="/angular-app/app/{{menuItem.id}}">{{menuItem.name}}</a>
    </li>
</div>

app.js

userApp.filter('matchAccessLevel', function() {
    return function( item, userAccessLevel, minAccessLevel ) {
        if( userAccessLevel >= minAccessLevel ) {
            return item;
        }
    }
});

Angularjs Solutions


Solution 1 - Angularjs

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

Solution 2 - Angularjs

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

Solution 3 - Angularjs

For CoffeeScript lovers:

userApp.filter 'matchAccessLevel', ->
  (items, userAccessLevel) ->
    item for item in items when userAccessLevel >= item.minAccess

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFisuView Question on Stackoverflow
Solution 1 - AngularjsLiviu T.View Answer on Stackoverflow
Solution 2 - AngularjsNathan Boolean TrujilloView Answer on Stackoverflow
Solution 3 - AngularjsfraczView Answer on Stackoverflow