Mister_L
Mister_L

Reputation: 2611

angular - directive on an element under ng-if not working

I have a page with tabs, here's an example of one of them:

<li ng-if="userData.isMaster">
 <a data-target="#debug-tab" data-toggle="tab" data-tab-name="debug" on-tab-shown>Debug</a>
</li>

This tab is similar to other tabs, with the exception that it is under ng-if. Each tab has an "on-tab-shown" directive which broadcasts an event each time the tab is shown. Inside each tab's controller there's an event listener that listens to this event. In other tabs, that are not under ng-if, the event is received by the listeners, but not in this tab. It is possible to replace the ng-if with ng-show to make it work, but are there better ways maybe?

Upvotes: 0

Views: 615

Answers (3)

There's no reason not to favor ng-show if it works better. All you're doing is adding to the DOM, or not. Per Angular's documentation:

ngIf differs from ngShow and ngHide in that ngIf completely removes and recreates the element in the DOM rather than changing its visibility via the display css property.

Here's the link if you'd like more info -- good luck!!

https://docs.angularjs.org/api/ng/directive/ngIf

Upvotes: 0

NicBright
NicBright

Reputation: 7799

I'm afraid no. The thing is, that ng-if completely blocks the linking of the element it's put on and all its children (in fact, they're even removed from the DOM). That's why ng-show works, because ng-show does not block any linking.

Upvotes: 0

lucky.hooligan
lucky.hooligan

Reputation: 81

If your ng-if is set to not show the tab (userData.isMaster == false), then the tab is removed from the DOM. Since it isn't on the DOM, it won't react to the broadcast. If you need it to react to the broadcast even though it isn't showing, you will need to use ng-show so it is simply hidden.

Upvotes: 1

Related Questions