AngularJS - Binding radio buttons to models with boolean values

后端 未结 7 633
梦如初夏
梦如初夏 2020-12-02 06:30

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

相关标签:
7条回答
  • 2020-12-02 07:36

    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:

    http://jsfiddle.net/hgxjv/4/

    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:

    http://jsfiddle.net/hgxjv/5/

    <input type="radio" name="response" value="{{choice.id}}" ng-model="question1.userChoiceId"/>
    

    That way you can just send {{question1.userChoiceId}} back to the server.

    0 讨论(0)
提交回复
热议问题