![]()
ng-disabled is an AngularJS directive that dynamically enables or disables HTML elements based on specified conditions. It is mainly used in forms, buttons, and input fields to prevent user interaction when certain conditions are met.
Topics Covered:
- What is
ng-disabled? - Basic Syntax
- Using
ng-disabledwith Boolean Values - Using
ng-disabledwith Expressions - Using
ng-disabledwith Functions - Example: Disabling a Button Until Conditions Are Met
- Example: Disabling an Input Field Based on Selection
- Difference Between
disabledandng-disabled - Best Practices
- Conclusion
1. What is ng-disabled?
ng-disabled is an AngularJS directive that binds a Boolean expression to the disabled attribute of an element.
If the expression evaluates to true, the element is disabled.
If the expression evaluates to false, the element remains enabled.
2. Basic Syntax
<button ng-disabled="isDisabled">Click Me</button>
$scope.isDisabled = true; // Button is disabled
- If
isDisabled = true, the button remains disabled. - If
isDisabled = false, the button becomes enabled.
3. Using ng-disabled with Boolean Values
<input type="text" ng-disabled="true" placeholder="This field is always disabled">
- The input field is always disabled.
<input type="text" ng-disabled="false" placeholder="This field is always enabled">
- The input field is always enabled.
4. Using ng-disabled with Expressions
<button ng-disabled="user.age < 18">Submit</button>
$scope.user = { age: 16 };
- If
user.ageis less than 18, the button is disabled. - If
user.ageis 18 or more, the button is enabled.
5. Using ng-disabled with Functions
<button ng-disabled="isFormInvalid()">Submit</button>
jsCopyEdit$scope.isFormInvalid = function() {
return $scope.name.length < 3; // Disable if name length < 3
};
- If the
namefield has less than 3 characters, the button remains disabled. - Once the
namefield has 3 or more characters, the button is enabled.
6. Example: Disabling a Button Until Conditions Are Met
<input type="text" ng-model="name" placeholder="Enter Name">
<button ng-disabled="!name">Submit</button>
- If the input field is empty, the button remains disabled.
- Once the user enters text, the button is enabled.
7. Example: Disabling an Input Field Based on Selection
<select ng-model="userType">
<option value="guest">Guest</option>
<option value="admin">Admin</option>
</select>
<input type="text" ng-disabled="userType == 'guest'" placeholder="Admins can type here">
- If “Guest” is selected, the input field is disabled.
- If “Admin” is selected, the input field is enabled.
8. Difference Between disabled and ng-disabled
| Feature | disabled | ng-disabled |
|---|---|---|
| Usage | Static attribute | Dynamic directive |
| Changes | Cannot change dynamically | Reacts to scope changes |
| Data Binding | No | Yes |
| Best for | Permanent disabling | Conditional disabling |
