在使用angularjs提交表单时,如何获取选中的单选按钮的值?

use*_*574 10 angularjs

我有几种形式.每个表单都有一些可能的单选按钮和一个提交按钮.只能检查一个单选按钮(每个无线电使用相同的名称属性).使用angularjs时,如何在提交表单时获取选中的单选按钮的值?@blesh建议对每个输入使用相同的ng模型,但请注意问题是输入标签是使用ng-repeat生成的,这就是问题开始的地方.当然,我需要一个输入只需一个按钮.它在以下plunker很好的描述,与@blesh的答案后打:http://plnkr.co/edit/5KTQRGdPv3dbP462vq1a?p=preview在里面,你可以看到,警报显示初始值,而不是当前的选定的输入.

Ben*_*esh 20

您的单选按钮的值将在您在输入元素上指定ng-model =""的任何范围属性上可用.尝试这样的事情:

JS

app.controller('MyCtrl', function($scope){ 
   $scope.submitForm = function (){
       alert($scope.radioValue):
   };

   $scope.radioValue = 1;
});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

并且,所以你可以看到它正常工作,这里是一个展示这个例子的傻瓜

  • 在花了一些时间阅读之后,我使用了ng-model ="$ parent.radioValue",因为ng-repeat创建了一个内部范围.现在它有效. (4认同)

Jet*_*hik 18

只需添加$parentng-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>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢哥们儿!$ parent允许您退出"ng-repeat"绑定,然后您可以访问$ scope变量值.真棒. (6认同)