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

Ban*_*San 7 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>
Run Code Online (Sandbox Code Playgroud)

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"
    }
]
Run Code Online (Sandbox Code Playgroud)

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

{"description":"New by Genre","group":"genre","type":"new"}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

谢谢大家

戴夫

And*_*ahl 1

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