AngularJS ng-if vs ng-hide/ng-show

Angular ng-if directive removes or recreates a portion of the DOM tree based on an expression (true or false). On the other hand ng-show (or ng-hide) shows or hides an element based on the expression using absence or presence of css class .ng-hide.

Example – Removing element from dom using ng-if

<div ng-app="myApp" ng-controller='MyCtrl'>
  <input type="checkbox" ng-model="checked" ng-init="checked=true">Check/uncheck to create/remove below div<br><br>
  <div ng-if="checked">
    Hello world
  </div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
  var module = angular.module('myApp', []);
  module.controller('MyCtrl', function($scope) {});
</script>
refresh

Dom when ng-if is true

dom-ng-if-true

Dom when ng-if is false

dom-ng-if-false

Example – Hiding element using ng-hide

<div ng-app="myApp" ng-controller='MyCtrl'>
  <label>Select checkbox to hide: <input type="checkbox" ng-model="doHide"></label><br/>
  <span ng-hide="doHide"><strong>Hide this text</strong></span>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script>
  var module = angular.module('myApp', []);
  module.controller('MyCtrl', function($scope) {});
</script>
refresh

Dom when ng-hide is false

dom-ng-hide-false

Dom when ng-hide is true

dom-ng-hide-true

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments