While learning AngularJS, it is very important to learn basic fundamentals of the framework. Many time it seems like couple of functions works exactly same way then also they all exist. But there may be minor but important difference between them.
In AngularJS, I came across these kind of two directives which works almost same way at the first site. But when I read more, I found they look like same but not the same at all.
<div ng-if="element/exists">Show this Div</div> <div ng-show="element/exists">Show this Div</div>
In AngularJS, ngIf & ngShow both will display element only if the expression passed in the directive returns true.
ngIf – It will insert the DOM element only when the expression passed in the directive returns true, but if the expression passed returns false, it will not insert the DOM element in the DOM tree. It means when the DOM elements is removed from DOM tree all the handlers or any events etc… attached to elements will get lost. So next time when the expression returns true for the directive, it will not have any handlers or events attached to it. We have to attached them again explicitly. Moreover ngIf creates a child scope.
ngShow/ngHide – It will not remove the DOM element from the DOM tree if expression in the directive returns false. It will show/hide DOM element with display property of CSS as per the expression. All the handlers or any events attached to the elements will not be removed whatever the expression returns. Moreover ngShow/ngHide does not create scope.
I guess, ngIf is better when we needed the DOM to be loaded conditionally as it will help load page bit faster compared to ngShow/ngHide. But there is a thin line in deciding which of these directives should we use. It totally depends on the requirement of the DOM.