javascript - AngularJS ng-model 将对象转换为字符串

标签 javascript angularjs

我的 HTML 文件中有以下内容:

    <td style="width: 200px;">
        <span ng-repeat="list in listGroups">
            <label for="{{ list.description }}" />{{ list.description }}</label>
            <input ng-model="$parent.listGroup" id="listGroup-{{ list.value }}"  name="listGroups" value="{{ list }}" type="radio" />
        </span>
   </td>

listGroups 包含:

[
    {
        "description": "New by Territory",
        "group": "product",
        "type": "new"
    },
    {
        "description": "New by Genre",
        "group": "genre",
        "type": "new"
    },
    {
        "description": "Charts by Territory",
        "group": "product",
        "type": "chart"
    },
    {
        "description": "Charts by Genre",
        "group": "genre",
        "type": "chart"
    }
]

当我点击单选按钮时,listGroup(在 ng-model 中设置)变为,例如:

{"description":"New by Genre","group":"genre","type":"new"}

当我用 typeof $scope.listGroup 查看列表组时,我发现它现在是一个字符串!

因此,我无法在 HTML 页面其余部分的其他绑定(bind)中访问它的属性。

在这种情况下,我想要 ng-show="listGroup.group == 'genre'"

这里发生了什么,更重要的是,我如何让它做我想让它做的事情,即将对象保持为对象?

谢谢大家

戴夫

最佳答案

问题是输入的value 属性只接受strings,不接受objects(检查here)。当您执行此操作时:value="{{ list }}",您基本上是在执行 input.value = list.toString()

一种可能的解决方法是使用 ng-repeat 指令的 $index。示例:http://jsfiddle.net/bmleite/cKttd/

关于javascript - AngularJS ng-model 将对象转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14832405/

相关文章:

javascript - 使用 JavaScript 注入(inject)任意 HTML 片段

javascript - 在类组件中使用react-i18next

javascript - 使用 Angular js 的 Controller 中的函数

jquery - 将 jQuery 与backbone.js/angular.js/ember.js 混合使用有什么问题?

angularjs - ng-view 在 angularjs 中的嵌套

javascript - AngularJs 中两个模块之间的通信

javascript - REGEXP js 点不起作用

javascript - 在替换中使用 Javascript 非捕获组

javascript - 点击重叠的 div

javascript - Angularjs promise 未及时解决