使用ng-model设置布尔值时遇到问题

时间:2015-04-13 16:49:36

标签: javascript angularjs

我无法使用ng-model将布尔值设置为true。当用户单击单选按钮时,不是将布尔值更改为true,而是给布尔值赋予整个对象。

这是我的HTML:

<div ng-repeat="choice in questions[counter].choices" class="answer">
  <input type="radio" name="options" value="{{choice}}" id="{{choice}}" ng-model="choice.selected" ng-value="true"/>
  <label class="radio" for="{{choice}}">
    {{choice.selected}}
    <h3>{{choice.text}}</h3>
  </label>
</div>

对象:

    $scope.questions = [
        {
        question: "Question1 text",
        choices: [
          {id: 1, text: "choice 1", correct: true,  selected: false},
          {id: 2, text: "choice 2", correct: false, selected: false},
          {id: 3, text: "choice 3", correct: false, selected: false},
          {id: 4, text: "choice 4", correct: false, selected: false}
        ]
    },
        {
        question: "Question2 text",
        choices: [
          {id: 1, text: "choice 1", correct: true,  selected: false},
          {id: 2, text: "choice 2", correct: false, selected: false},
          {id: 3, text: "choice 3", correct: false, selected: false},
          {id: 4, text: "choice 4", correct: false, selected: false}
        ]
    }
];

这是一个Plunkr

我做错了什么?

2 个答案:

答案 0 :(得分:0)

单选按钮不会评估为真/假值,它们会评估它们绑定的对象。如果您想要真/假值,请使用复选框。

<input type="checkbox" name="{{choice.text}}" ng-model="choice.selected" ng-value="true"/>

答案 1 :(得分:0)

将您的输入更新为以下内容:

<input type="radio" name="options" id="{{choice}}"
ng-model="choice.selected" ng-value="true" ng-change="updateOptions(questions[counter].choices,choice);"/>

并将此功能添加到您的控制器:

  $scope.updateOptions = function(choices, choice){
    for(var i=0; i<choices.length; i++){
      choices[i].selected = choices[i].id==choice.id;
    }
  }