如何将 ng-if 与 ng-repeat 一起使用? [英] How to use ng-if with ng-repeat?

查看:27
本文介绍了如何将 ng-if 与 ng-repeat 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 

但是以下不起作用(注意 ng-show 现在是 ng-if):

 

路由对象看起来像

路线:{'/home': { label: 'Home', nav: true },'/contact': { label: 'Contact', nav: false},//等等}

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

<块引用>

错误:多个指令 [ngIf, ngRepeat] 要求嵌入:

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

解决方案

可能有更好的解决方案,但是看完上面的回复,您可以尝试制作自己的自定义过滤器:

angular.module('yourModule').filter('filterNavItems', function() {返回函数(输入){var inputArray = [];for(输入中的var项目){inputArray.push(input[item]);}返回 inputArray.filter(function(v) { return v.nav; });};});

然后使用它:

Plunker 简介:http://plnkr.co/edit/srMbxK?p=preview

I have a simple nav object setup that lists the nav items (and whether they should appear in the primary nav or not). It seems though when I try to mix ng-if with ng-repeat, things fall apart, but when I mix ng-show with ng-repeat it works fine (but I end up with a bunch of hidden elements that I don't want appended to the DOM).

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

But the following doesn't work (note the ng-show is now ng-if):

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

The routes object looks like

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

I receive the following error when trying to use ng-if:

Error: Multiple directives [ngIf, ngRepeat] asking for transclusion on:

I guess it's trying to tell me that I can't state it's declaration for existing twice. I could use ng-if on an inner element, but I think I would still end up with a bunch of empty outer a tags.

解决方案

There's probably a better solution, but after reading the replies above, you can try making your own custom filter:

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; });
  };
});

Then to use it:

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

Here's the Plunker: http://plnkr.co/edit/srMbxK?p=preview

这篇关于如何将 ng-if 与 ng-repeat 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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