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; } } });
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With