AngularJS - 绑定单选按钮与布尔值模型
我有一个问题,结合单选按钮的对象,其属性具有布尔值。我试图显示从$资源获取考题。
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
<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:真属性不引起要选择的单选按钮。如果我封装在引号中的布尔值,它的工作原理。
With this example object, the "isUserAnswer: true" property does not cause the radio button to be selected. If I encapsulate the boolean values in quotes, it works.
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序列化的引号来封装这些值。有另一种方式来建立模型,而不会改变我的模型结构结合?
Unfortunately my REST service treats that property as a boolean and it will be difficult to change the JSON serialization to encapsulate those values in quotes. Is there another way to set up the model binding without changing the structure of my model?
在Angularjs正确的做法是用 NG-值
的车型非字符串值。
The correct approach in Angularjs is to use ng-value
for non-string values of models.
修改您的code是这样的:
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>
参考:直接从马的嘴