Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;         }     } }); 
like image 806
Fisu Avatar asked Mar 04 '13 06:03

Fisu


People also ask

How do I filter in NG repeat?

The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

What is the correct method to create custom filters in angular?

To create custom filter, we need to just register the filter in factory function in our module. This uses the "filterProvider" internally. By default new filter function takes the input value as the first argument and factory function will return the new filter.

What is correct way to apply multiple filters in angular?

Using filters in view templates Filters can be applied to the result of another filter. This is called "chaining" and uses the following syntax: {{ expression | filter1 | filter2 | ... }} E.g. the markup {{ 1234 | number:2 }} formats the number 1234 with 2 decimal points using the number filter.


1 Answers

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

like image 51
Liviu T. Avatar answered Sep 22 '22 21:09

Liviu T.