AngularJS ng-if – conditional dom tree

Angular ng-if directive removes or recreates a portion of the DOM tree based on an expression (true or false).

Usage:

<ANY
  ng-if="expression">
...
</ANY>

Example – ng-if without animation

<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

Example – ng-if with animation

<style>
.animate-if {
  background-color:lightblue; width: 100px;
}
.animate-if.ng-enter, .animate-if.ng-leave {
  transition:all 1s;
}
.animate-if.ng-enter, .animate-if.ng-leave.ng-leave-active {
  opacity:0;
}
.animate-if.ng-leave, .animate-if.ng-enter.ng-enter-active {
  opacity:1;
}
</style>

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

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.min.js"></script>
<script>
  var module = angular.module('myApp', ["ngAnimate"]);
  module.controller('MyCtrl', function($scope) {});
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments