如何在ng-repeat中使用ng-if?

克里斯 :

我有一个简单的导航对象设置,其中列出了导航项(以及它们是否应出现在主导航中)。看来,当我尝试将ng-if与ng-repeat混合使用时,事情会分崩离析,但是当我将ng-show与ng-repeat混合使用时,它可以正常工作(但是最终我得到了一堆隐藏的元素,但我没有想要附加到DOM)。

   <section class="nav">
        <a  ng-repeat="(key, item) in route.routes"
            ng-href="{{key}}"
            ng-show="item.nav"
        >
                {{item.label}}
        </a>
    </section>

但是以下操作无效(请注意,ng-show现在是ng-if):

    <section class="nav">
    <a  ng-repeat="(key, item) in route.routes"
        ng-href="{{key}}"
        ng-if="item.nav"
    >
            {{item.label}}
    </a>
</section>

路线对象看起来像

routes: {
    '/home': { label: 'Home', nav: true },
    '/contact': { label: 'Contact', nav: false},
   // etc
}

尝试使用时收到以下错误ng-if

错误:多个指令[ngIf,ngRepeat]要求在以下位置进行包含:

我想这是想告诉我,我不能声明它是两次存在的声明。我可以ng-if在一个内部元素上使用,但是我想我最终还是会得到一堆空的外部a标签。

丛沃:

可能有更好的解决方案,但是在阅读了以上答复之后,您可以尝试制作自己的自定义过滤器:

angular.module('yourModule').filter('filterNavItems', function() {
  return function(input) {
    var inputArray = [];

    for(var item in input) {
      inputArray.push(input[item]);
    }

    return inputArray.filter(function(v) { return v.nav; });
  };
});

然后使用它:

<section class="nav">
    <a  ng-repeat="(key, item) in routes | filterNavItems"
        ng-href="{{key}}">
            {{item.label}}
    </a>
</section>

这是Plunker:http://plnkr.co/edit/srMbxK?p = preview

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在ng-repeat中使用ng-options绑定<select> ng-model

如何在ng-repeat中使用$ error.required?

如何在ng-repeat中使用动态订单

AngularJS:如何在ng-repeat中使用$索引

如何在Web API中使用angular ng-repeat?

如何在ng-repeat angularjs中使用多重响应?

如何在ng-repeat中使用角度值

如何在angularjs中使用ng-repeat

如何在另一个ng-repeat中使用ng-repeat范围

如何在AngularJS中使用ng-repeat动态生成ng-model =“ my _ {{$ index}}”“?

如何在ng-repeat中使用ng-if创建新行?

如何在 ng-repeat 中使用 ng-if 来应用 css 类

如何在angularjs中使用ng-click显示ng-repeat的确切内容

如何在ng-repeat中使用ng-init将值绑定到变量?

我如何在ng-repeat中使用ng-repeat但内部ng-repeat应该一次打印一个数组的值

在ng-repeat中使用外键

在Pokeapi中使用ng-repeat

如何在angularJS中使用ng-if,ng-else

如何在ng-if中使用数据?

如何在angularjs中使用ng-repeat和array时创建对象

AngularJS:如何在 HTML 中使用两个 ng-repeat 显示深度对象值

如何在ng-repeat中使用$ index启用类并显示DIV?

如何在图片地图区域标签中使用ng-repeat?

如何在AngularJs中使用ng-repeat过滤(键,值)?

如何在ng-repeat中使用anchorScroll()在索引x处具有开始视图

如何在AngularJS中使用ng-repeat遍历键和值?

如何在AngularJS ng-repeat中使用ES6 Map

如何在 angularjs 中使用 ng-repeat 时显示特定项目内的数据?

如何在表主体中使用ng-repeat包含多行?