簡體   English   中英

如何將 ng-if 與 ng-repeat 一起使用?

[英]How to use ng-if with ng-repeat?

我有一個簡單的導航對象設置,它列出了導航項目(以及它們是否應該出現在主導航中)。 似乎當我嘗試將 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

而不是ng-if你應該在你的ng-repeat上使用過濾器( http://docs.angularjs.org/api/ng.filter:filter )來從你的列表中排除某些項目。

我也遇到了這個問題,並找到了幾種解決方法。

我嘗試的第一件事是將ng-ifng-repeat成一個自定義指令。 我很快就會把它推送到 github,但它很笨拙。

更簡單的方法是修改您的route.routes集合(或創建一個占位符集合)

$scope.filteredRoutes = {};
angular.forEach($scope.route.routes, function(item, key) {
    if (item.nav) { $scope.filteredRoutes[key] = item; }
};

在你看來

...
<a  ng-repeat="(key, item) in filteredRoutes"
...

如果您需要動態更新,只需設置手表等。

這個單行如何使用$filter

$scope.filteredRoutes = $filter('filter')($scope.route.routes, function(route){
  return route.nav;
});

您應該在ng-repeat中使用過濾器,而不是使用ng-if

這應該有效:

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

警告:我還沒有真正測試過這段代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM