ng-change directive is used to specify the custom behavior that execute when you change the value of an HTML element.
The ng-change directive requires the ng-model directive to be existing.
In AngularJS, the ng-change directive will not override the HTML element’s original onchange event, both will be executed.
In AngularJS, the ng-change directive expression is evaluated immediately, unlike the JavaScript onchange event, which only activated at the end of a change.
The ng-change directive is compiling at the priority level “0” (zero is a default priority level).
The ng-change expression is only executed when a change in the input value causes a new value to be committed to the model.
It will not be evaluated:
If the value returned from the $parser transformation pipeline has not changed
If the input has continued to be invalid since the model will stay null.
If the model is changed programmatically and not by a change to the input value
It is used to define an expression that execute when the text of an element will be cut.
Sample coding for ng-change directive in AngularJS:
Tryit<!DOCTYPE html><html><head><title>Wikitechy AngularJS Tutorials</title><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
angular.min.js"></script></head><body><h2>Wikitechy ng-change Directive in AngularJS Tutorials </h2><div ng-app="myApp" ng-controller="myCtrl"><lable>Enter the text</lable><input type="text" ng-change="changeFunc()" ng-model =”myValue”><h3>The input field has been changed {{ count }} times </h3></div><script>angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.changeFunc = function() {
$scope.count++;
};
}]);</script></body></html>
Code Explanation for ng-change directive in AngularJS:
AngularJS is distributed as a JavaScript file, and can be added to a HTML page with a <script> tag.
The AngularJS application is defined by ng-app="myApp". The application runs inside the <div> tag. It’s also used to define a <body> tag as a root element. and ng-controller=” myCtrl” is used to define a controller.
The ng-change= “changeFunc()” is called a changeFunc() function when a change in the input value causes a new value to be committed to the model.
Here the ng-model is bind an input field value to AngularJS application variable by using ng-model name as “myValue”.
angular.module() function is used to create a module for application. We have passed an empty array to it.
Here we have assign the function() as value to $scope.changeFunc
Here the count value is increased by one by using $scope.count++
Sample Output for ng-change directive in AngularJS:
The output shows that when the user start to typing the input field, the count value will be increased by one by using the ng-change directive which one is called the changeFunc() function.
The output displays a count value in the content “The input field has been changed 18 times.”