AngularJS ng-if vs ng-show


These functions are very similar in behaviour. The difference is that ng-if removes elements from the DOM. If there are large parts of the code that will not be shown, then ng-if is the way to go. ng-show will only hide the elements but will keep all the handlers.


The ngIf directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.


The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element.


<div ng-repeat="user in userCollection">
  <p ng-if="user.hasTreeLegs">I am special
    <!-- some complicated DOM -->
  <p ng-show="user.hasSubscribed">I am aweosme
    <!-- switch this setting on and off -->


It depends from the type of usage, but often one is more suitable than the other (e.g., if 95% of the time the element is not needed, use ng-if; if you need to toggle the DOM element's visibility, use ng-show).

When in doubt, use ng-if and test!

Note: ng-if creates a new isolated scope, whereas ng-show and ng-hide don't. Use $ if parent scope property is not directly accessible in it.