我有几种形式。每个表单都有一些可能的单选按钮和一个提交按钮。只能检查一个单选按钮(每个无线电使用相同的名称属性)。使用angularjs时,如何在提交表单时获取选中的单选按钮的值? @blesh建议对每个输入使用相同的ng模型,但请注意问题是输入标签是使用ng-repeat生成的,这就是问题开始的地方。当然,我需要一个输入只需一个按钮。在使用@blesh的答案后,在下面的plunker中对它进行了详细描述:http://plnkr.co/edit/5KTQRGdPv3dbP462vq1a?p=preview在其中,您可以看到警报显示初始值而不是当前所选输入。
答案 0 :(得分:20)
您的单选按钮的值将在您在输入元素上指定ng-model =“”的任何范围属性上可用。尝试这样的事情:
JS
app.controller('MyCtrl', function($scope){
$scope.submitForm = function (){
alert($scope.radioValue):
};
$scope.radioValue = 1;
});
HTML
<form name="myForm" ng-controller="MyCtrl" ng-submit="submitForm()">
<label><input type="radio" name="test" ng-model="radioValue" value="1"/> One</label>
<label><input type="radio" name="test" ng-model="radioValue" value="2"/> Two</label>
<label><input type="radio" name="test" ng-model="radioValue" value="3"/> Three</label>
<div>currently selected: {{radioValue}}</div>
<button type="submit">Submit</button>
</form>
而且,你可以看到它有效,here is a plunker demonstrating the example
答案 1 :(得分:18)
只需在$parent
中添加ng-model
。
<form name="myForm" ng-submit="submitForm()">
<label data-ng-repeat="i in [1,2,3]"><input type="radio" name="test" ng-model="$parent.radioValue" value="{{i}}"/>{{i}}</label>
<div>currently selected: {{radioValue}}</div>
<button type="submit">Submit</button>
</form>
答案 2 :(得分:0)
与ng-value结合
app.controller('MyCtrl', function($scope){
$scope.submitForm = function() {
*****
};
$scope.radioBtn = {
name: 'radioButton'
};
$scope.radioValueOne = {"id": "1", "value": "whatever you want"};
$scope.radioValueTwo = {"id": "2", "value": "whatever you want"};
$scope.radioValueThree = {"id": "3", "value": "whatever you want"};
});
<form name="myForm" ng-controller="MyCtrl" ng-submit="submitForm()">
<label><input type="radio" name="test" ng-model="radioBtn.name" ng-value="radioValueOne"/> One</label>
<label><input type="radio" name="test" ng-model="radioBtn.name" ng-value="radioValueTwo"/> Two</label>
<label><input type="radio" name="test" ng-model="radioBtn.name" ng-value="radioValueThree"/> Three</label>
<div>currently selected: {{radioBtn.name}}</div>
<button type="submit">Submit</button>
</form>
答案 3 :(得分:0)
我遇到了这个问题,发现了一个非常简单和干净的解决方案。这是你应该做的。
在您的控制器中,创建一个具有任何名称的空对象(&#34; radioValue&#34;在这种情况下)。
在您的HTML文件中,使用相同的&nbsp-model&#39;每个单选按钮/输入的名称与对象加入的名称相同&#39; name&#39;每个单选按钮的属性(每个按钮也应该相同)用句点(。)分隔,如代码片段所示。
控制器
var radioValue={};
...
...
console.log($scope.radiovalue) //use JSON.strinigify if naccessary
HTML文件
<input type="radio" name="somename" ng-model="radioValue.somename" value="1"/>
<input type="radio" name="somename" ng-model="radioValue.somename" value="2"/>
<input type="radio" name="somename" ng-model="radioValue.somename" value="3"/>
//Don't forget to mention value attribute. ng-model does the work by identifying the radio-buttons/inputs by value attribute
您应该期待的输出
{"somename":"1"} //if radio-button with value "1" is selected.