AngularJS - 将单选按钮绑定到具有布尔值的模型 [英] AngularJS - Binding radio buttons to models with boolean values

查看:31
本文介绍了AngularJS - 将单选按钮绑定到具有布尔值的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将单选按钮绑定到属性具有布尔值的对象时遇到问题.我正在尝试显示从 $resource 中检索到的试题.

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: true"属性不会导致单选按钮被选中.如果我将布尔值封装在引号中,它会起作用.

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?

这是显示非工作和工作对象的 jsFiddle

推荐答案

Angularjs 中正确的做法是将 ng-value 用于模型的非字符串值.

The correct approach in Angularjs is to use ng-value for non-string values of models.

像这样修改你的代码:

<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>

参考:直接来自马口

这篇关于AngularJS - 将单选按钮绑定到具有布尔值的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆