如何使用NG-如果与NG-重复? [英] How to use ng-if with ng-repeat?

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

问题描述

我有一个简单的导航对象的设置,其中列出了导航项目(以及他们是否应该出现在主导航与否)。看来,虽然当我尝试混合NG-如果与NG重复,事情土崩瓦解,但是当我混NG-节目NG-重复它工作正常(但我结束了一堆隐藏的元素,我不知道的要添加到DOM)。

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>

但下面不工作(注意 NG-节目现在 NG-如果

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

尝试使用,当我收到以下错误 NG-如果

错误:多重指令[ngIf,ngRepeat]要求transclusion上:

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

我想这是想告诉我,我不能说出它的声明为现有的两倍。我可以使用 NG-如果内部元件上,但我想我仍然会结束了一堆空的外 A 标记。

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

然后使用它:

<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=$p$pview

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

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