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
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 */
<div ng-show=”showSecretData”>Secret data</div>
/*same can be re-written using ng-hide directive */
<div ng-hide=”!showSecretData”>Secret data</div>
<div ng-show=”name == ‘myName’”>Some data</div>
<div ng-show=”Display()”>Some data</div>
Demo of ng-show / ng-hide directive
ng-show / ng-hidedirectives 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.
<div ng-switch on=”showSecretData”>
<div ng-switch-when=”true”>You can see my secret!</div>
<div ng-switch-default>Secret is not visible for you!</div>
Demo of ng-switch and ng-if directive
ng-show / ng-hidedirectives 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-ifis a version of
ng-switchwith single condition,
ng-switchis 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 */
<div ng-include="header.html"> </div>