javascript - Why does an Angular model prevent a checkbox from being checked by default? -
i'm using angularjs website , want use checkbox. first created checkbox this:
<input type="checkbox" checked>
i can of course remove , add checked
liking have checked default or not. add model (the model not defined in controller yet):
<input type="checkbox" ng-model="settings.myswitch" checked>
the checkbox still displays, of sudden checked
has no effect @ anymore; checkbox unchecked default.
why oh why model prevent checked
having effect? tips welcome!
that because when element rendered browser sets checked
property angular processes ng-model on check box (whose value falsy) , gets unchecked. instead if ng-checked="true"
work (because ng-checked
directive sets property after ng-model processed priority lower ng-model
). but model's initial state messed (if using 1.3.x+), ng-checked
not update state of ng-model. set ng-model
value true instead.
just demonstration using ng-init
(you should set ng-model initial value in controller instead).
<input type="checkbox" ng-init="settings.myswitch=true" ng-model="settings.myswitch" />
see demo comparison:-
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <div ng-app> <p> ng-checked {{settings.myswitch}} <input type="checkbox" ng-checked="true" ng-model="settings.myswitch" /> <p> proper initialization {{settings.myswitch1}} <input type="checkbox" ng-init="settings.myswitch1=true" ng-model="settings.myswitch1" /> </div>
Comments
Post a Comment