In this article I will explain with an example, how to use AngularJS ng-change directive with CheckBoxes.
For illustration purposes this article will explain how to show hide (toggle) HTML DIV on CheckBox click i.e. checked – unchecked or selected – unselected using ng-show and ng-change directives.
Show Hide (Toggle) HTML DIV on CheckBox click using ng-show and ng-change
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML markup consists of an HTML DIV and a CheckBox. The HTML DIV has been assigned ng-show directive. 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.
The CheckBox has been assigned ng-change directive. When the CheckBox is clicked i.e. checked – unchecked or selected – unselected, the ShowHide function of the Controller gets called.
Inside the function, the value of the IsVisible variable is reversed i.e. if it is true then it set to false and vice versa. This makes the HTML DIV toggle when the CheckBox is clicked i.e. checked – unchecked or selected – unselected.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
//This will 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>
<div ng-app="MyApp" ng-controller="MyController">
<label for="chkPassport">
<input type="checkbox" id="chkPassport" ng-model="ShowPassport" ng-change="ShowHide()" />
Do you have Passport?
</label>
<hr />
<div ng-show="IsVisible">
Passport Number:
<input type="text" id="txtPassportNumber" />
</div>
</div>
</body>
</html>
Screenshot
Demo
Downloads