I am having a problem binding radio buttons to an object whose properties have boolean values. I am trying to display exam questions retrieved from a $resource.
HTML
The correct approach in Angularjs is to use ng-value
for non-string values of models.
Modify your code like this:
<label data-ng-repeat="choice in question.choices">
<input type="radio" name="response" data-ng-model="choice.isUserAnswer" data-ng-value="true" />
{{choice.text}}
</label>
Ref: Straight from the horse's mouth
The way your radios are set up in the fiddle - sharing the same model - will cause only the last group to show a checked radio if you decide to quote all of the truthy values. A more solid approach will involve giving the individual groups their own model, and set the value as a unique attribute of the radios, such as the id:
$scope.radioMod = 1;
$scope.radioMod2 = 2;
Here is a representation of the new html:
<label data-ng-repeat="choice2 in question2.choices">
<input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
{{choice2.text}}
</label>
And a fiddle.
I tried changing value="true"
to ng-value="true"
, and it seems to work.
<input type="radio" name="response2" data-ng-model="choice.isUserAnswer" ng-value="true" />
Also, to get both inputs to work in your example, you'd have to give different name to each input -- e.g. response
should become response1
and response2
.
You might take a look at this:
https://github.com/michaelmoussa/ng-boolean-radio/
This guy wrote a custom directive to get around the issue that "true" and "false" are strings, not booleans.
<label class="rate-hit">
<input type="radio" ng-model="st.result" ng-value="true" ng-checked="st.result">
Hit
</label>
<label class="rate-miss">
<input type="radio" ng-model="st.result" ng-value="false" ng-checked="!st.result">
Miss
</label>
if you are using boolean variable to bind the radio button. please refer below sample code
<div ng-repeat="book in books">
<input type="radio" ng-checked="book.selected"
ng-click="function($event)">
</div>