In this article I will explain with an example, how to use ng-change directive in AngularJS.
 
 

HTML Markup

The following HTML Markup consists of:
DIV – For applying ng-app and ng-controller AngularJS directives.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
CheckBox – For show and hide Div.
The CheckBox has been assigned with following AngularJS directives.
ng-change – Execute when the value of the input field changes.
ng-model – Binds the value to CheckBox.
Note: If you want to learn more about ng-model directives, please refer my article Using ng-model directive in AngularJS.
 
DIV – For show and hide when CheckBox is clicked.
The HTML DIV has been assigned ng-show directive.
Note: If you want to learn more about ng-show directives, please refer my article Simple AngularJS ng-show and ng-hide Tutorial with example.
 
The value of ng-show directive has been set using the variable IsVisible which is initially set to false and hence, the HTML DIV is hidden when page loads.
<div ng-app="MyApp" ng-controller="MyController">
    <label for="chkPassport">
        <input id="chkPassport" type="checkbox" ng-change="ShowHide()" ng-model="ShowPassport" />
        Do you have Passport?
    </label>
    <hr />
    <div ng-show="IsVisible">
        Passport Number: <input type="text" />
    </div>
</div>
 
 

Implementing ng-change Directive

Inside the HTML Markup, the following AngularJS script is inherited:
1. angular.min.js
When the CheckBox is clicked, the ShowHide function of the Controller gets called.
Inside this function, the value of the IsVisible variable is reversed i.e. if it is true then, it is set to false and vice versa.
This makes the HTML DIV toggle when the CheckBox is clicked i.e. checked (selected) or unchecked (unselected).
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', [])
    app.controller('MyController', function ($scope) {
        // Hide the DIV by default.
        $scope.IsVisible = false;
        $scope.ShowHide = function () {
            // If DIV is visible it will be hidden and vice versa.
            $scope.IsVisible = $scope.ShowPassport;
        }
    });
</script>
 
 

Screenshot

ng-change Example in AngularJS
 
 

Demo

 
 

Downloads