使用angularjs提交表单时,如何获取选中单选按钮的值? [英] How can I get the value of the checked radio button when submitting a form using angularjs?

查看:28
本文介绍了使用angularjs提交表单时,如何获取选中单选按钮的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个表格.每个表单都有几个可能的单选按钮和一个提交按钮.只能选中一个单选按钮(对每个单选使用相同的名称属性).提交表单时,如何使用 angularjs 获取选中的单选按钮的值?@blesh 建议对每个输入使用相同的 ng-model,但请注意问题在于输入标签是使用 ng-repeat 生成的,这就是问题的开始.当然,我当然只需要一个按钮来进行一堆输入.在玩过@blesh 的答案后,它在以下 plunker 中有很好的描述:http://plnkr.co/edit/5KTQRGdPv3dbP462vq1a?p=preview 在其中,您可以看到警报显示的是初始值,而不是当前选择的输入.

I have a few forms. Each form have a few possible radio buttons and a submit button. Only one radio button can be checked (using the same name attribute for each radio). How can I get the checked radio button's value when the form is submitted, using angularjs? @blesh advised to use the same ng-model for each input, but note that the problem is that the input tags are generated using ng-repeat, and this is where the problem starts. I need, of course, naturally, only one button for a bunch of inputs. It is well described in the following plunker, after playing with @blesh 's Answer: http://plnkr.co/edit/5KTQRGdPv3dbP462vq1a?p=preview In it, you can see that the alert shows the initial value and not the current selected input.

推荐答案

您的单选按钮的值将适用于您在 input 元素上分配了 ng-model="" 的任何范围属性.尝试这样的事情:

Your radio button's value will be available on whatever scope property you've assigned ng-model="" to on the input element. Try something like this:

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>

而且,您可以看到它的工作原理,这里有一个 plunker 演示示例

And, so you can see it working, here is a plunker demonstrating the example

这篇关于使用angularjs提交表单时,如何获取选中单选按钮的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆