Hello Friends, In this tutorial we are going to learn ng-change directive in Angular Js. Unlike onchange event of JavaScript ng-change directive evaluates the expression immediately whereas onchange event triggers at the of change when the input field loses its focus.

Introduction:

The ng-change directive specifies that what to do when any changes in the value of the HTML element occurs. ng-change directives evaluate the expression immediately whereas JavaScript onchange event triggers at the end of the change when input field loses its focus. ng-change directives need the ng-model directive to be present. ng-change event triggers only if actual changes in the input field occur not changes made from JavaScript.

ng-change

Syntax:

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

Parameter explanation:

expression: It specifies an expression that needs to evaluate when a change in the value of element occurs.

Example 1:

<!DOCTYPE html> 
<html> 
<head>
<title>
Angular Js Demo
</title>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
 
<script> 
 angular.module('myApp', []) 
 .controller('myCtrl', ['$scope', function($scope) { 
 $scope.count = 0; 
 $scope.Counter = function() { 
 $scope.count++; 
 }; 
 }]); 
</script> 
</head>
<body ng-app="myApp"> 
<div ng-controller="myCtrl"> 
 <p>Enter something in the input field:</p> 
 <input type="text" ng-change="Counter()" ng-model="myValue" /> 
 <p>The input field has changed {{count}} times.</p> 
</div>

</body> 
</html>

You can view the demo of the above application here.

Example 2:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>Angular Js Demo</title>
<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">
<div class="container">
<div class="col-md-3 well" ng-init="count=0">
Courses: <select ng-change="ngChangeCount()" class="form-control" ng-model="course" ng-options="cr.course as cr.course for cr in courses"></select>
<pre> ({{course}}) ng-Change {{count}} </pre>
</div>
</div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller('myCtrl', ['$scope', function ($scope) {
$scope.course = "Angular";
$scope.courses = [{ course: ".NET" }, { course: "SQL Server" }, { course: "Angular Js" }];
$scope.ngChangeCount = function () {
$scope.count = $scope.count + 1;
}
}]);
</script>
</body>
</html>

You can view the demo of Example 2 here.

Hope you have understood what is ng-change directive in Angular Js and what is the difference between an onchange event of Javascript and ng-change directive in Angular Js.

View More:

Thank You.

Leave a Comment