Angular.js: ngSwitch to show/hide rather than add/remove DOM elements

Viewed 2436

As I've recently found out, ngSwitch acts a bit like ngIf, in that it outright removes elements from the DOM rather than just hide them. Now in my application this strikes me as both needlessly expensive and potentially problematic down the line (if I need to access properties of my hidden DOM elements). At the same time I like the cleanliness of the ngSwitch syntax as opposed to a bunch of different ngShow directives (which would not allow me to include a 'default' behaviour either). Is there any way I can modify the way this directive works to have it merely hide elements, not remove them altogether? Thanks.

3 Answers

OK, I understood better your need and I have the same need before. I advice you to use ngSwitch with custom directives like this :

<div ng-switch="mode">
  <directive-a ng-switch-when="a"></directive-a>
  <directive-b ng-switch-when="b">...</directive-b>
  <directive-c ng-switch-default>...</directive-c>
</div>

and in the definitions of your directives directiveA, directiveB and directiveC you use the templateUrl wich will use the cache from the second call of the directive.

The second approach is to use ng-show on every directive but I prefer the ng-switch because it let the dom lighter.

I know this is a bit old but I faced the same issue today and I managed to cache segments views by not using ngSwitch but directly the [hidden] attributes with the segment condition this way :

<ion-segment [(ngModel)]="segmentName">
  <ion-segment-button value="profile">
    Profile
  </ion-segment-button>
  <ion-segment-button value="friends">
    Friends
  </ion-segment-button>
</ion-segment>
<page-profile [hidden]="segmentName != 'profile'" ></page-profile>
<page-friends [hidden]="segmentName != 'friends'" ></page-friends>

Just replace ngSwitchCase by the [hidden] conditional

No, there isn't any way to keep nodes hidden as ngShow and ngHide do if you use ngSwitch. Only the ngSwitchWhen node will be created if its condition is true, all others are commented. The advantage of ngSwitch is that the dom will be lighter.

Related