Chris Chris - 2 months ago 6
AngularJS Question

How to use ng-if with ng-repeat?

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.

Answer

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

Comments