AngularJS ng-model converts an object to a string

In my HTML file, I have the following:

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

The list of groups contains:

 [ { "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" } ] 

When I click the radio button, listGroup (set in the ng model) becomes, for example:

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

When I look at the list group with typeof $scope.listGroup , I see that now it is a string!

Thus, I cannot access its properties in other bindings on the rest of the HTML page.

In this case, I want ng-show="listGroup.group == 'genre'"

What happens here and, more importantly, how do I get it to do what I want it to execute an object that stores the object as an object?

Thanks everyone

Dave

+7
source share
4 answers

The problem is that the input value attribute only accepts strings, not objects (here). When you do this: value="{{ list }}" , you basically do input.value = list.toString() .

A possible workaround is to use the $index directive ng-repeat . Example: http://jsfiddle.net/bmleite/cKttd/

+4
source

Why do you want to have an object as an ng model? This is why your listGroup variable becomes a string, since the ng model only works with strings. If you have a complex object that you want to use with ng-model, you must create a directive and implement a parser and formatter, for example: How to do two-way filtering in angular.js?

+1
source

Now you can use ng-value .

Example

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

+1
source

You can also use JSON.parse (object-in-string), but I think it's better to use the @bmleite solution. Just throw it away - if someone has a different use case.

0
source

All Articles