In this article I will explain a simple tutorial with an example, how to use the ng-disabled directive in AngularJS.
This article will illustrate how to enable or disable TextBox on CheckBox click i.e. checked – unchecked or selected – unselected using ng-disabled directive in AngularJS.
AngularJS: ng-disabled Tutorial with example
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 TextBox and a CheckBox. The HTML TextBox has been assigned ng-disabled directive. The value of ng- disabled directive has been set using the variable IsDisabled which is initially set to true and hence the HTML TextBox is disabled when page loads.
The CheckBox has been assigned ng-change directive. When the CheckBox is clicked i.e. checked – unchecked or selected – unselected, the EnableDisable function of the Controller gets called.
Inside the function, the value of the IsDisabled variable is reversed i.e. if it is true then it set to false and vice versa. This makes the HTML TextBox enabled or disabled 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 disable the TextBox by default.
$scope.IsDisabled = true;
$scope.EnableDisable = function () {
//If TextBox is disabled it will be enabled and vice versa.
$scope.IsDisabled = !$scope.HasPassport;
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<label for="chkPassport">
<input type="checkbox" id="chkPassport" ng-model="HasPassport" ng-change="EnableDisable()" />
Do you have Passport?
</label>
<hr />
<div>
Passport Number:
<input type="text" id="txtPassportNumber" ng-disabled="IsDisabled"/>
</div>
</div>
</body>
</html>
Screenshot
Demo
Downloads