Courtney Courtney - 1 year ago 77
AngularJS Question

How to make a input disabled by default using angular directives

How do I make a textual input field disabled by default and have it toggled using a checkbox. I am getting the checkbox to toggle the input field between an enabled and a disabled state but I cannot get the input field to be disabled by default even though I set the checkbox to true when the page loads.

I tried this method but it doesn't disable the input field until I toggle the checkbox to off and on:

<input type="text" ng-disabled="restaurant.valid_shortname" ng-model="restaurant.shortname" >
<input type="checkbox" ng-model="restaurant.valid_shortname" ng-checked="true"/>

What I would like to do is have the checkbox checked when the page loads which as a reseult disables the input field

Answer Source

from the docs of ng-checked:

Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.

The correct way would probably be to set the restaurant.valid_shortname to true inside your controller. You could use ng-init as well if you insist on doing it in your template. That would look something like this:

<input ng-init="restaurant.valid_shortname = true" type="text" ng-disabled="restaurant.valid_shortname" ng-model="restaurant.shortname" >
<input type="checkbox" ng-model="restaurant.valid_shortname"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download