当前位置: 首页 > 工具软件 > ng-dynamic > 使用案例 >

AngularJS – Conditional Display using ng-show / ng-hide, ng-if, ng-include, ng-switch

鞠通
2023-12-01

http://realityonweb.com/angularjs/angularjs-conditional-display-using-ng-show-ng-hide-ng-if-ng-include-ng-switch/

Hiding or showing parts of a DOM based on some conditions is a common requirement. AngularJS has four different directives (ng-show / ng-hide, ng-if, ng-include, ng-switch), which are used to conditionally display or hide the HTML DOM elements.

Conditional display using ng-show/ng-hide

The ng-show / ng-hide directives require a boolean value to evaluate the visual state. This boolean value may come from a variable or a function.

Demo of ng-show / ng-hide directive

src="http://realityonweb.com/AngularJS/ng-show-hide/index.html" height="400" width="100%" border="0" class="demo-frame" style="box-sizing: border-box;">

Download this demo example of ng-hide / ng-show directive

ng-show / ng-hide directives apply ‘display:none’ to hide the DOM elements, hidden elements are not removed from the DOM tree.

Conditional display using ng-switch directive

ng-show / ng-hide simply apply ‘display:none’ to hide the DOM elements. ng-switch directive can be used to physically remove or add the DOM elements. It is similar to the traditional switch, casestatement.

Demo of ng-switch and ng-if directive

src="http://realityonweb.com/AngularJS/ng-switch/index.html" height="450" width="100%" border="0" class="demo-frame" style="box-sizing: border-box;">
Download this demo example of ng-switch and ng-if

ng-show / ng-hide directives are easy to use but, will have performance issue when used to large number of DOM nodes.

Conditional display using ng-if directive

ng-If directive is similar to the ng-switch (adding / removing the DOM elements from the DOM tree) and it can be used simply as ng-hide /ng-show (require a boolean value to evaluate visual state). Demo example of the ng-if is along with the ng-switch above. If you check all the framework, a success message come using the ng-if.

ng-if is a version of ng-switch with single condition, ng-switch is more verbose, it should not be used in simple use-case.

Conditional display using ng-include

ng-include directive can be used to display block of dynamic content. It can fetch external HTML template depending on a specific condition. It can be used with a fixed part of page like header, footer

Demo of ng-include directive

src="http://realityonweb.com/AngularJS/tabs-ng-include/index.html" height="300" width="100%" border="0" class="demo-frame" style="box-sizing: border-box;">
Download the demo example of ng-include directive


 类似资料: