AngularJS - 如何使用 ng-repeat 构建自定义过滤器以有条件地返回项目 [英] AngularJS - How to structure a custom filter with ng-repeat to return items conditionally

查看:20
本文介绍了AngularJS - 如何使用 ng-repeat 构建自定义过滤器以有条件地返回项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个打印列表项的 ng-repeat.我想编写一个自定义过滤器,以便仅在条件为真时才打印列表项.

我似乎结构错误,因为变量似乎没有传递到过滤器.

index.php

app.js

userApp.filter('matchAccessLevel', function() {返回函数(项目,userAccessLevel,minAccessLevel){if( userAccessLevel >= minAccessLevel ) {归还物品;}}});

解决方案

过滤器不适用于数组中的单个项目,它们会将整个数组转换为另一个数组.

userApp.filter('matchAccessLevel', function() {返回函数(项目,用户访问级别){var 过滤 = [];angular.forEach(项目,功能(项目){if(userAccessLevel >= item.minAccess) {过滤.推(项目);}});返回过滤;};});

看到这个 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-repeat 构建自定义过滤器以有条件地返回项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆