javascript 如何使用对象作为单选按钮的 ng 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23570173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use an object as ng-value of a radio button?
提问by Sr.Richie
Is there any way to use an object for ng-value of a radio button?
有没有办法将对象用于单选按钮的 ng 值?
Imagine you have a radio button whose ng-model is an object, like this:
假设您有一个单选按钮,其 ng-model 是一个对象,如下所示:
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
我知道我可以使用 ng-change 指令。我只是想知道我问的是不是可能的,这将是非常聪明的
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:
我想在模型中保存按钮的值及其标签。因此,假设我的控制器中有一个名为 ImpactOptions 的数组和一个用于创建按钮的 ng-repeat 指令:
<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"/>
回答by Brocco
You can have an object as the value in ng-value
:
您可以将一个对象作为 中的值ng-value
:
<div ng-app>
<input type="radio" ng-model="modelObject" ng-value="{val:1, text:'text'}"/>
<p>>{{modelObject|json}}<</p>
</div>
The values in ng-value
can also be dynamic as well per request:
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>
回答by Diana Nassar
You can use ng-value="option"
:
您可以使用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?
需要id
时可从获取,$scope.option.id
需要text
时可从$scope.option.text
. 在这里检查我的答案。这对你的情况有用吗?