Alternative to ng-show/-hide or how to load only relevant section of DOM

匿名 (未验证) 提交于 2019-12-03 02:12:02

问题:

When using ng-show/-hide, the content included in those blocks initially displays on the user screen. Only after few milliseconds (after angular.js has loaded and executed) does the right block show up in ng-show.

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

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

回答1:

To avoid the "flash of uncompiled 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 head section of your HTML, you will need to add this to your CSS file, and ensure it loads at the top of your page:

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

Note that you only need to use these directives on your initial page. Content that is pulled in later (e.g., via ng-include, ng-view, etc.) will be compiled by Angular before the browser renders.

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

Some alternatives to ng-show/ng-hide are ng-include, ng-switch and (since v1.1.5) ng-if:

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

See also https://stackoverflow.com/a/12584774/215945 for an example of ng-switch working together with ng-include.

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



回答2:

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

[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



回答3:

Per Mark Rajcok's fine answer, here's a CodePen showing ng-show, ng-switch, and ng-if in action, so you can compare the approaches, and see differences in how the conditional content is actually rendered.

Note that some people feel that ng-show is a little faster than ng-switch and ng-if for file-based templates. But you can use $templateCache to preload your templates at bootstrap time, reducing or eliminating that advantage. Using ng-switch and ng-if, you no longer have to deal with hidden conditional content being in the DOM when it's not needed, and prevent expressions on that content being evaluated by Angular at inopportune times. That saves you processing resources you don't need to waste, and avoids errors that can be thrown when something's evaluated prematurely.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!