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.
ng-if is better in this regard. Using it in place of ng-show will prevent the heavy content from being rendered in the first place if the expression is false. However, its strength is also its weakness, because if the user hides the chart and then shows it again, the content is rendered from scratch each time.
Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.
Definition and UsageThe ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.
Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
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
Instead of ng-if
you should use a filter (http://docs.angularjs.org/api/ng.filter:filter) on you ng-repeat
to exclude certain items from your list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With