我有一个问题,将单选按钮绑定到一个对象,其属性有布尔值。我试图显示从$资源检索的考试问题。

HTML:

<label data-ng-repeat="choice in question.choices">
  <input type="radio" name="response" data-ng-model="choice.isUserAnswer" value="true" />
  {{choice.text}}
</label>

JS:

$scope.question = {
    questionText: "This is a test question.",
    choices: [{
            id: 1,
            text: "Choice 1",
            isUserAnswer: false
        }, {
            id: 2,
            text: "Choice 2",
            isUserAnswer: true
        }, {
            id: 3,
            text: "Choice 3",
            isUserAnswer: false
        }]
};   

对于这个示例对象,“isUserAnswer: true”属性不会导致单选按钮被选中。如果我将布尔值封装在引号中,它可以工作。

JS:

$scope.question = {
    questionText: "This is a test question.",
    choices: [{
            id: 1,
            text: "Choice 1",
            isUserAnswer: "false"
        }, {
            id: 2,
            text: "Choice 2",
            isUserAnswer: "true"
        }, {
            id: 3,
            text: "Choice 3",
            isUserAnswer: "false"
        }]
};   

不幸的是,我的REST服务将该属性视为布尔值,因此很难更改JSON序列化以将这些值封装在引号中。是否有另一种方法可以在不改变模型结构的情况下设置模型绑定?

下面是显示非工作对象和工作对象的jsFiddle


当前回答

在小提琴中设置收音机的方式(共享相同的模型)将导致只有最后一组显示选中的收音机,如果您决定引用所有的真值。一个更可靠的方法是为每个组提供自己的模型,并将值设置为无线电的唯一属性,例如id:

$scope.radioMod = 1;
$scope.radioMod2 = 2;

下面是新html的一个表示:

<label data-ng-repeat="choice2 in question2.choices">
            <input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
                {{choice2.text}}
        </label>

还有一把小提琴。

其他回答

在小提琴中设置收音机的方式(共享相同的模型)将导致只有最后一组显示选中的收音机,如果您决定引用所有的真值。一个更可靠的方法是为每个组提供自己的模型,并将值设置为无线电的唯一属性,例如id:

$scope.radioMod = 1;
$scope.radioMod2 = 2;

下面是新html的一个表示:

<label data-ng-repeat="choice2 in question2.choices">
            <input type="radio" name="response2" data-ng-model="radioMod2" value="{{choice2.id}}"/>
                {{choice2.text}}
        </label>

还有一把小提琴。

 <label class="rate-hit">
     <input type="radio" ng-model="st.result" ng-value="true" ng-checked="st.result">
     Hit
 </label>
 &nbsp;&nbsp;
 <label class="rate-miss">
     <input type="radio" ng-model="st.result" ng-value="false" ng-checked="!st.result">
     Miss
 </label>

我试着将value="true"改为ng-value="true",似乎可以工作。

<input type=“radio” name=“response2” data-ng-model=“choice.isUserAnswer” ng-value=“true” />

此外,为了让两个输入都在你的例子中工作,你必须给每个输入赋予不同的名称——例如,response应该变成response1和response2。

你可以看看这个:

https://github.com/michaelmoussa/ng-boolean-radio/

这家伙写了一个自定义指令来解决“true”和“false”是字符串而不是布尔值的问题。

如果使用布尔变量绑定单选按钮。请参考下面的示例代码

<div ng-repeat="book in books"> 
<input type="radio" ng-checked="book.selected"  
ng-click="function($event)">                        
</div>