4

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"/>
4

2 回答 2

5

您可以将对象作为值ng-value

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

示例小提琴

每个请求中的值ng-value也可以是动态的:

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

更新的示例小提琴

于 2014-05-09T17:56:59.510 回答
1

您可以使用ng-value="option"

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

当您需要时,id您可以从中获得它$scope.option.id,当您需要时,text您可以从$scope.option.text. 在这里检查我的答案。这对你的情况有用吗?

于 2014-05-10T10:00:15.117 回答