ng-change example in AngularJS


    ng-change event directive is fired when there is change in the input value or in other words whenever your HTML element changes ng-change is triggered.

ng-change syntax : 

<ng-change
  ng-change="expression">
...
</ng-change>

Lets see this event directive in action with some simple examples.

Example 1: Change in Checkbox element
    So in this example we are incrementing the counter($scope.counter) whenever the checkbox is selected or unselected. The output gif would explain it much better.

<!DOCTYPE html>
<html>
<script
 src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
 <div ng-controller="myCtrl">
  <p>Check :</p>

  <input type="checkbox" ng-model="myValue" ng-change="myFunc()" />

  <p>The Checkbox has changed {{count}} times.</p>
 </div>

 <script>
  angular.module('myApp', []).controller('myCtrl',
    [ '$scope', function($scope) {
     $scope.count = 0;
     $scope.myFunc = function() {
      $scope.count++;
     };
    } ]);
 </script>
 
</body>
</html>


Output : 
Example 2 : Change in Dropdown element
   In this example, we have invoked the counter incrementing function when the drop down element is changed

<!DOCTYPE html>
<head>
<script
 src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp">
 <div ng-controller="myCtrl">
  <select ng-change="myFunc()" class="form-control"
   ng-model="selectDemo">
   <option>ONE</option>
   <option>TWO</option>
   <option>THREE</option>
  </select> <br /> <br />

  <p>
   Total number of times drop down selected:<b>{{count}} </b>
  </p>
 </div>

 <script>
  var app = angular.module("myApp", []);
  app.controller('myCtrl', [ '$scope', function($scope) {
   $scope.count = 0;
   $scope.myFunc = function() {
    $scope.count = $scope.count + 1;
   }
  } ]);
 </script>
</body>
</html>


Output 

Hope  these examples gives a good understanding on ng-change event directive in AngularJS.




Reactions:

0 comments :

Post a Comment