Sr.Richie
Sr.Richie

Reputation: 5740

How to use an object as ng-value of a radio button?

Is there any way to use an object for ng-value of a radio button?

Imagine you have a radio button whose ng-model is an object, like this:

modelObject: {val:'', text:''}

And this would be the radio button:

<input type="radio" ng-model="data.modelObject" ng-value=""/>

Is there a way to do something like the following (obviously it doesn't work)

<input type="radio" model="data.modelObject" ng-value="val:option.id, text:option.text"/>

? Thanks

I know I can use the ng-change directive. I'm just wondering if what I am asking it's possible, it would be very smart

EDIT: as requested in the comments, I am giving a bit of extra info on my setup.

I want to save in the model both the value of the button and its label. So let's say I have an array in my controller called impactOptions and a ng-repeat directive to create the buttons:

<div ng-repeat="option in impactOptions" >
    <input type="radio" ng-model="data.modelObject.val" id="rbGroup{{option.id}} ng-value="option.id"/>
    <label for="rbGroup{{option.id}}">{{option.text}}</label>
</div>

The problem with this setup is that in that way I'm only saving the value of the button, while I would like to also save it's label. I really need it later.

I'm looking for a way to do something like this

<input type="radio" model="data.modelObject" ng-value="val:option.id, text:option.text"/>

Upvotes: 4

Views: 14876

Answers (2)

Brocco
Brocco

Reputation: 64863

You can have an object as the value in ng-value:

<div ng-app>
    <input type="radio" ng-model="modelObject" ng-value="{val:1, text:'text'}"/>
    <p>>{{modelObject|json}}<</p>
</div>

example fiddle

The values in ng-value can also be dynamic as well per request:

<div ng-app ng-init="opt={id: 1, text: 'some text'}">
    <input type="radio" ng-model="modelObject" ng-value="{val:opt.id, text:opt.text}"/>
    <p>>{{modelObject|json}}<</p>
</div>

updated example fiddle

Upvotes: 5

Diana Nassar
Diana Nassar

Reputation: 2303

You can use ng-value="option":

<input type="radio" model="data.modelObject" ng-value="option"/>

When you need id you can have it from $scope.option.id and when you need text you can access it from $scope.option.text. Check my answer here. Does this work for your case?

Upvotes: 1

Related Questions