AngularJS - 如何结构NG-重复有条件地返回项的自定义过滤器 [英] AngularJS - How to structure a custom filter with ng-repeat to return items conditionally
本文介绍了AngularJS - 如何结构NG-重复有条件地返回项的自定义过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个NG重复,打印列表项。我想写一个自定义过滤器,使该列表项将打印,只有当条件为真。
我似乎有结构错误的,因为它似乎变量没有得到通过的过滤器。
的index.php
< DIV NG秀=userDetails.username级=导航>
&所述p为H.;菜单&下; / P>
<李NG重复=菜单项菜单| matchAccessLevel:$ rootScope.userDetails.accessLevel:menuItem.minAccess |排序依据:'位置'>
<一个NG-HREF =/角应用程序/应用程序/ {{menuItem.id}}> {{menuItem.name}}< / A>
< /李>
< / DIV>
app.js
userApp.filter('matchAccessLevel',函数(){
返回功能(项目,userAccessLevel,minAccessLevel){
如果(userAccessLevel> = minAccessLevel){
归还物品;
}
}
});
解决方案
过滤器不要在阵中,他们整个数组转换为另一个数组中。个别项目工作
userApp.filter('matchAccessLevel',函数(){
返回功能(物品,userAccessLevel){
变种过滤= [];
angular.forEach(项目功能(项目){
如果(userAccessLevel> = item.minAccess){
filtered.push(项目);
}
});
返回过滤;
};
});
请参阅此 plnkr
*的总是检查参数的函数。它并不总是显而易见的是什么值。的
请参见过滤指南
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;
}
}
});
解决方案
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
这篇关于AngularJS - 如何结构NG-重复有条件地返回项的自定义过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文