How to use ng-if else in AngularJs

Angular 1.1.5 introduced ng-If directive. You can Use ng-if directive above 1.1.5 versions .

ng-if directive remove DOM element if expression return false. And if expression return true then it recreates a DOM tree again.

ng-if directive very different from ngshow and ngHide because ng-if removes and recreates the elements from DOM . But ngShow and ngHide handle visibility of element by setting display css property of CSS.

And heavy use of ng-if can effect application performance.

I am showing how ng-if directive work in AngularJs.

Plunker (Demo) - http://plnkr.co/edit/X5RYEEu1EEYCXac4PWf9?p=preview

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!doctype html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>How to use ng-if else in AngularJs</title>
   <script>
      var myApp = angular.module('myApp', []);
      myApp.controller('myController', function($scope) {
         $scope.showUserScore = true;
         $scope.showUserMobile = true;
      });
   </script>
</head>
<body ng-app="myApp">
   <div ng-controller="myController">
      <div ng-if="showUserScore"> Score - 1000 </div>
      <div ng-if="showUserMobile"> Contact Number - 55555-1111 </div>
   </div>
</body>
</html>
<!doctype html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <title>How to use ng-if else in AngularJs</title>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
   <script>
      var myApp = angular.module('myApp', []);
      myApp.controller('myController', function($scope) {
         $scope.showUserScore = true;
         $scope.showUserMobile = true;
      });
   </script>
</head>

<body ng-app="myApp">
   <div ng-controller="myController">
      <div ng-if="showUserScore"> Score - 1000 </div>
      <div ng-if="showUserMobile"> Contact Number - 55555-1111 </div>
   </div>
</body>

</html>

Need a help , connect with us on skype


Comments