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

时间:2013-02-12 12:18:39

标签: 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的listgroup时,我发现它现在是一个字符串!

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

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

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

全部谢谢

戴夫

4 个答案:

答案 0 :(得分:4)

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

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

答案 1 :(得分:2)

现在可以使用ng-value

实施例

<input ng-model="$parent.listGroup" id="listGroup-{{ list.value }}" name="listGroups" ng-value="{{ list }}" type="radio" />

答案 2 :(得分:1)

为什么要将对象作为ng模型?这就是导致listGroup变量成为字符串的原因,因为ng-model只适用于字符串。如果你有一个想要与ng-model一起使用的复杂对象,你应该创建一个指令并实现一个解析器和一个格式化器,如下所示:How to do two-way filtering in angular.js?

答案 3 :(得分:0)

您也可以使用JSON.parse(object-in-string),但我认为我更喜欢@bmleite解决方案。把它扔到那里 - 因为有人有不同的用例。