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.
/*ng-show / hide */Secret data/*same can be re-written using ng-hide directive */Secret dataSome dataSome data
Demo of ng-show / ng-hide directive
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, case
statement.
/*ng-switch*/You can see my secret!Secret is not visible for you!
Demo of ng-switch and ng-if directive
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 ofng-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
/* ng-include */
Leave a Reply