AngularJS ng-if ng-show and ng-hide
Learn the difference between ng-if, which adds or removes elements from the DOM, and ng-show/ng-hide, which only toggle their CSS visibility.
ng-if: Adding and Removing Elements
ng-if completely removes an element (and everything inside it) from the DOM when its expression is false, and re-creates it when the expression becomes true again. Because the element is destroyed rather than hidden, it also gets a brand-new child scope each time it is added back.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-init="loggedIn=false">
<input type="checkbox" ng-model="loggedIn"> Logged in
<p ng-if="loggedIn">Welcome back!</p>
</div>
</body>
</html>ng-show and ng-hide: Toggling Visibility
ng-show and ng-hide keep the element in the DOM at all times. Instead of adding or removing it, AngularJS toggles the CSS display property — ng-show sets display:none when its expression is false, and ng-hide sets display:none when its expression is true.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-init="loggedIn=false">
<input type="checkbox" ng-model="loggedIn"> Logged in
<p ng-show="loggedIn">Welcome back! (ng-show)</p>
<p ng-hide="loggedIn">Please log in. (ng-hide)</p>
</div>
</body>
</html>Why the Difference Matters
Because ng-if actually removes elements, it is a better choice for content that is expensive to render, holds sensitive data that should not sit hidden in the page source, or needs a fresh scope every time it appears. ng-show and ng-hide are cheaper for elements that toggle frequently, since AngularJS only flips a CSS property instead of rebuilding the element.
- Use ng-if when the element should not exist in the page at all while hidden
- Use ng-show/ng-hide when the element toggles often and recreating it would be wasteful
- Remember ng-if creates a new child scope each time; ng-show/ng-hide do not
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-init="showDetails=false">
<button ng-click="showDetails=!showDetails">Toggle</button>
<div ng-if="showDetails">
<p>These details are removed from the DOM when hidden.</p>
</div>
</div>
</body>
</html>Exercise: AngularJS Directives
What is a key difference between ng-if and ng-show?