Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-model converts object to string

I have the following in my HTML file:

    <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 listGroups 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 a radio button the listGroup (set in ng-model) becomes, for example:

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

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

As such, I can't access it's properties in the other bindings in the rest of the HTML page.

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

What's happening here and, more importantly, how do I make it do what I want it to do, which is keep the object as an object?

Thanks all

Dave

like image 492
BanksySan Avatar asked Feb 12 '13 12:02

BanksySan


2 Answers

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

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

like image 62
bmleite Avatar answered Oct 19 '22 23:10

bmleite


It is now possible to use ng-value.

Example

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

like image 42
Liably Avatar answered Oct 19 '22 22:10

Liably