Alternative to ng-show / -hide or how to load only the corresponding DOM section

When using ng-show / -hide, the content included in these blocks is initially displayed on the user screen. Only a few milliseconds (after loading and executing angular.js) does the right block appear in ng-show.

Is there a better way than ng-show / -hide to load only the relevant data section in the DOM?

The problem with ng-view is that I can only have one page, so I need to switch the behavior of many DOM sections based on the current state.

+53
angularjs
Dec 28 '12 at 11:17
source share
3 answers

To avoid a β€œflash of uncompressed content”, use ng-bind instead of {{}} or use ng-cloak :

 <span ng-cloak ng-show="show">Hello, {{name}}!</span> 

If you use ng-cloak and you do not load Angular.js in the header section of your HTML, you need to add this to your CSS file and ensure that it loads at the top of the page:

 [ng\:cloak], [ng-cloak], .ng-cloak { display: none; } 

Please note that you need to use these directives only on the start page. Content that is pulled later (e.g. via ng-include, ng-view, etc.) will be compiled by Angular before the browser displays.

Is there a better way to load data other than ng-show / hide, into which only the corresponding section in the DOM is loaded.

Some alternatives to ng-show / ng-hide ng-include , ng-switch and (since version 1.1.5) ng-if :

 <div ng-include src="someModelPropertySetToThePartialYouWantToLoadRightNow"></div> 

See also https://stackoverflow.com/a/212930//ng-switch example working with ng-include.

Note that ng-switch and ng-if add / remove DOM elements, while ng-show / hide only modifies CSS (if that matters to you).

+105
Dec 28
source share

I used the ng-cloak trick and it doesn't seem to work so well. After the Angular documentation, I added the following to my CSS:

 [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { display: none !important; } 

See: http://docs.angularjs.org/api/ng.directive:ngCloak

+2
07 Feb '14 at 21:17
source share

There is a good answer on the Rajcok brand, here is CodePen showing ng-show, ng-switch and ng-if in action, so you can compare approaches and see the differences in how conditional content is actually displayed.

Please note that some people find ng-show a bit faster than ng-switch and ng-if for file templates. But you can use $ templateCache to preload templates at boot time, reducing or eliminating this advantage. Using ng-switch and ng-if, you no longer need to deal with hidden conditional content located in the DOM when it is not needed, and not allow expressions in this content evaluated by Angular at inappropriate times. This saves your processing resources that you do not need to spend, and avoids the errors that can be thrown when something is evaluated prematurely.

+1
Nov 02 '13 at 23:46
source share



All Articles