AngularJS | ng-change Directive
The ng-change Directive in AngularJS is used whenever the value of an input element changes. The expression is evaluated immediately whenever there is a change in the input value. It requires a ng-model directive to be present. It is triggered whenever there is any single change in the input. It can be used with input elements like <input>, <textarea>, <checkbox> and <select>
Syntax:
<element ng-change="expression"> Contents... </element>
Where expression refers to the expression to execute whenever the value of input changes.
Example 1: This example uses ng-change Directive to display/hide some content using checkbox.
<!DOCTYPE html><html> <head> <title>ng-change Directive</title> <script src= </script> <script type="text/javascript"> var app = angular.module('geek', []); app.controller('app', function ($scope) { $scope.show = function () { if ($scope.check == true) $scope.result = true; else $scope.result = false; } }); </script></head> <body style="padding: 30px"> <div ng-app="geek" ng-controller="app"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-change Directive</h2> Check to show/hide details <input type="checkbox" ng-change="show()" ng-model="check"> <br><br> <div style="padding:10px; border:1px solid black; width:30%;color:green" ng-show='result'> GeeksforGeeks is the computer science portal for geeks. </div> </div></body> </html> |
Output:
Before checked the checkbox:
After checked the checkbox:
Example 2: This example returns the number of times state of checkbox is changed and also the current state of checkbox.
<!DOCTYPE html><html> <head> <title>ng-change Directive</title> <script src= </script></head> <body ng-app="geek" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>ng-change Directive</h2> <div ng-controller="prop"> <div> Are you a developer: <input type="checkbox" ng-model="isTrue" ng-change="cnt=cnt+1" ng-init="cnt=0"/> </div> Count: {{cnt}} <pre>{{isTrue}}</pre> </div> <script> var app = angular.module("geek", []); app.controller('prop', ['$scope', function ($app) { $app.isTrue = false; }]); </script></body> </html> |
Output:
Before checked the checkbox:
After checked the checkbox:


