单选按钮和其他元素之间的数据绑定无法按预期工作

时间:2015-02-09 21:18:24

标签: angularjs angularjs-ng-repeat angular-ui

我有以下JSON答案:
我想将此提交给数据库只有一个答案可以有" IS_CORRECT"带有价值的旗帜" Y:

"Answers": [ 
       { "ANSWER_ID": 5, "DESCRIPTION": "Answer 3", "IS_CORRECT": "N" }, 
       { "ANSWER_ID": 4, "DESCRIPTION": "Answer 2", "IS_CORRECT": N }, 
       { "ANSWER_ID": 3, "DESCRIPTION": "Answer 1", "IS_CORRECT": "N" } 
    ]

在我的html中,我使用ng-repeat来循环我的答案,然后为每个答案创建一个单选按钮。

    <div  class="control-group" ng-repeat="answer in Answers>
           <input type="radio" ng-model="answer.IS_CORRECT" value="Y" name="answer"/>  
    </div>

我的问题是,当我检查Answer_id 5是否正确时,它会更新&#34; IS_CORRECT&#34;从我的模型到#34; Y&#34;但它不会将AnsWer 4和3&#34; IS_CORRECT更新为N&#39;

你能给我一些建议吗

1 个答案:

答案 0 :(得分:2)

您正在使用单选按钮作为复选框。更好的方法是节省当前值:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.js"></script>
    </head>
    <body ng-app="testApp">
        <div ng-controller="controller">
            <div class="control-group" ng-repeat="answer in answers">
                <label>
                    {{answer.DESCRIPTION}}
                    <input type="radio" ng-model="$parent.correctAnswer" ng-value="answer" name="correct_answer">
                </label>
            </div>
            Correct Answer: {{correctAnswer.DESCRIPTION}}
        </div>
    </body>
    <script>
    var app = angular.module('testApp', []);
    app.controller('controller', function($scope) {
        $scope.answers = [ 
           { "ANSWER_ID": 5, "DESCRIPTION": "Answer 3"}, 
           { "ANSWER_ID": 4, "DESCRIPTION": "Answer 2"}, 
           { "ANSWER_ID": 3, "DESCRIPTION": "Answer 1"} 
        ];
        $scope.correctAnswer = $scope.answers[1];
    });
    </script>
</html>