2013-02-12 67 views
7

我在HTML文件中的以下内容:AngularJS NG-模型转换对象为字符串

<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(组-model)变为,例如:

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

当我看到有typeof $scope.listGroup listgroup,我看到它是一个现在串!

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

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

这里发生了什么,更重要的是,我怎么让它做我想做的事情,这是保持对象作为一个对象?

感谢所有

戴夫

回答

1

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

4

的问题是,输入的value属性只接受 ,而不是对象(检查here)。当你这样做:value="{{ list }}",你基本上在做input.value = list.toString()

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

+0

此外,不要使用'$ parent.',它可以在未来给你带来问题。 – bmleite 2013-02-12 14:04:24

1

现在可以使用ng-value

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

0

你也JSON.parse(对象的字符串),但我想我喜欢@bmleite更好的解决方案。只是把它扔到那里 - 因为有人有不同的用例。