How to disable a button depending on a checkbox’s state in AngularJS ?
In this article, we will learn to disable the button depending upon the check-box status in Angular. We will use the Angular JS directive named ng-disabled to disable the button by unchecking the box. Please refer to AngularJS ng-disabled Directive.
The ng-disabled directive is used to enable or disable the HTML elements. If the expression inside the ng-disabled directive returns true then the HTML element would be disabled and vice versa.
Approach: Here in the example, we have taken a checkbox and based on the checkbox, we are checking that whether the submit button is to be enabled or disabled. Here ng-model directive is used for binding the checkbox with the submit button & the ng-disabled directive is to handle the disable or enable operations.
Here if the checkbox is checked it will return TRUE and that TRUE will be passed to the ng-disabled directive. As a result, the submit button would be disabled but we need to enable it whenever the checkbox is checked. So for that, we need to have a NOT operation at the ng-disabled directive so that whenever the checkbox returns TRUE, the value that will go to the ng-disabled directive will be FALSE so that the submit button is enabled.
Example:
HTML
<!DOCTYPE html> < html lang = "en" > < head > <!-- Including the Angular JS CDN --> < script src = "http://code.angularjs.org/1.2.0/angular.min.js" > </ script > </ head > < body > <!-- Defining the Angular Application --> < div ng-app = "" > <!-- Here we define the ng-model to the checkbox so that we can refer to it whether it checked or not --> < input type = "checkbox" name = "isAgreed" ng-model = "isAgreed" /> < p >I agree with the Terms and Conditions</ p > < br /> <!-- If the checkbox is checked then button would be enabled and if not checked then button would be disabled --> < button ng-disabled = "!isAgreed" >Submit</ button > </ div > </ body > </ html > |
Output: