Open In App

AngularJS ng-change Directive

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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 an 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>

Parameter Value:

  • expression: It refers to the expression to execute whenever the value of input changes.

Example 1: This example uses the ng-change Directive to display/hide some content using the checkbox. 

HTML




<!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:

 

Example 2: This example returns the number of times the state of the checkbox is changed and also the current state of the checkbox. 

HTML




<!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>
    <h3>ng-change Directive</h3>
    <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:

 



Last Updated : 01 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads