AngularJS Tutorial => Ng-if Vs Ng-show

Example

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.

ng-if

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.

ng-show

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.

Example

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

Conclusion

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 $parent.property if parent scope property is not directly accessible in it.

Got any AngularJS Question?

Ask any AngularJS Questions and Get Instant Answers from ChatGPT AI: ChatGPT answer me! pdf PDF - Download AngularJS for free Previous Next

Từ khóa » Ng-show Vs Ng-hide Vs Ng-if