简体   繁体   中英

Why does an Angular model prevent a checkbox from being checked by default?

I'm using Angularjs for a website and I now want to use a checkbox. I first created a checkbox like this:

<input type="checkbox" checked>

I can of course remove and add checked to my liking to have it checked by default or not. I now add a model to it (the model is not defined in the controller yet):

<input type="checkbox" ng-model="settings.mySwitch" checked>

The checkbox still displays, but all of a sudden the checked has no effect at all anymore; the checkbox is always unchecked by default.

Why oh why does the model prevent the checked from having any effect? All tips are welcome!

That is because when as the element is rendered browser sets checked property but then angular processes ng-model on the check box (whose value is falsy) and it gets unchecked. Instead if you do ng-checked="true" it will work (because ng-checked directive sets the property after ng-model is processed as its priority is lower than ng-model ). But your model's initial state will get messed up (if using 1.3.x+), as ng-checked will not update the state of ng-model . So just set the ng-model value to true instead.

Just for demonstration i am using ng-init (You should set the ng-model initial value in the controller instead).

 <input type="checkbox" ng-init="settings.mySwitch=true" ng-model="settings.mySwitch" />

See Demo with comparison:-

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <div ng-app> <p> With ng-checked {{settings.mySwitch}} <input type="checkbox" ng-checked="true" ng-model="settings.mySwitch" /> <p> WIth Proper Initialization {{settings.mySwitch1}} <input type="checkbox" ng-init="settings.mySwitch1=true" ng-model="settings.mySwitch1" /> </div> 

Instead use ng-checked like this :

<input type="checkbox" ng-model="settings.mySwitch" ng-checked="true">

Edit: @PSL is right you should be using ng-init instead as it will mess up your ng-model .

<input type="checkbox" ng-init="settings.mySwitch=true" ng-model="settings.mySwitch" />

It is because of the initial value of settings.mySwitch . If you want the checkbox to be checked by default then instead of adding checked property you should set the initial value to true because when angular processes the template it will get its value and render the checked property accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM