AngularJS - Binding radio buttons to models with boolean values
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>
That's an odd approach with isUserAnswer
. Are you really going to send all three choices back to the server where it will loop through each one checking for isUserAnswer == true
? If so, you can try this:
HTML:
<input type="radio" name="response" value="true" ng-click="setChoiceForQuestion(question1, choice)"/>
JavaScript:
$scope.setChoiceForQuestion = function (q, c) { angular.forEach(q.choices, function (c) { c.isUserAnswer = false; }); c.isUserAnswer = true;};
Alternatively, I'd recommend changing your tack:
<input type="radio" name="response" value="{{choice.id}}" ng-model="question1.userChoiceId"/>
That way you can just send {{question1.userChoiceId}}
back to the server.
<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>