简体   繁体   中英

html input type radio checked doesn't work with ng-model

I want my radio-input in the html preselected. It works fine when i just write:

<input type="radio" name="trackingOption" id="trackingOption" value="1"> Yes
<input type="radio" name="trackingOption" id="trackingOption" value="0" checked=""> No

But as soon as I add my ng-model for interact with my javaScript, the checked Option is gone

<input type="radio" name="trackingOption" ng-model="tracking" id="trackingOption" value="0" checked=""> No

Anyone know why "checked" doesn't work anymore with ng-model?!

您分配的值= 0,这就是为什么检查不了的原因,所以不要这样分配

The solution is to insert a ng-init expression which says which ng-model has the ng-value

<div ng-init="tracking=0">
     <input type="radio" name="trackingOption" ng-model="tracking" ng-value="1" id="trackingOption" value="1"> Yes
     <input type="radio" name="trackingOption" ng-model="tracking" ng-value="0" id="trackingOption" value="0" checked=""> No
</div>

You should be able to interact with your model:

<input type="radio" name="trackingOption" ng-model="tracking" id="trackingOption" value="0"> No

<input type="radio" name="trackingOption" ng-model="tracking" id="trackingOption2" value="1"> Yes

The value is: {{tracking}}

See that the value of tracking gets updated each time you click on the other input. Then you need this part in your directive:

scope.$watch('tracking', (newValue, oldValue) => { //doyourstuffhere } )

Is this what you want?

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