Angular JS在点击时传递所选单选按钮的值

时间:2017-01-29 12:24:16

标签: angularjs angularjs-ng-model

在视图中有两个单选按钮列表

L1

    <input type="radio" name="SET1" ng-model="SET1Selected" value="S1"> S1
    <input type="radio" name="SET1" ng-model="SET1Selected" value="S2"> S2
    <input type="radio" name="SET1" ng-model="SET1Selected" value="S3"> S3

L2

    <input type="radio" name="SET2" ng-model="SET2Selected" values="S4"> S4
    <input type="radio" name="SET2" ng-model="SET2Selected" value="S5"> S5
    <input type="radio" name="SET2" ng-model="SET2Selected" value="S6"> S6

    <button ng-click="submitRadioBtn()"></button>

Angular JS

    var app = angular.module("myApp", []);
    app.controller("myCtrl", ['$scope', function($scope) {  

     $scope.submitRadioBtn=function(){
       var valfromSET1 = $scope.SET1Selected;
        var valfromSET2 = $scope.SET2Selected; 
     }
    }]);  

我必须在点击时获得两个单选按钮的值。

1 个答案:

答案 0 :(得分:1)

您的代码应该没有任何问题。只需确保您已将ng-controller包含在 div 标记之外。

<强>样本

 var app = angular.module("myApp", []);
 app.controller("myCtrl", ['$scope', function($scope) {

   $scope.submitRadioBtn = function() {
     var valfromSET1 = $scope.SET1Selected;
     var valfromSET2 = $scope.SET2Selected;
     console.log(valfromSET1);
     console.log(valfromSET2);
   }
 }]);
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <meta charset="utf-8" />
  <script src="https://code.angularjs.org/1.4.7/angular.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="myCtrl">
  <div class="row">
  <input type="radio" name="SET1" ng-model="SET1Selected" value="S1"> S1
  <input type="radio" name="SET1" ng-model="SET1Selected" value="S2"> S2
  <input type="radio" name="SET1" ng-model="SET1Selected" value="S3"> S3
  </div>
  <div class="row">
  <input type="radio" name="SET2" ng-model="SET2Selected" values="S4"> S4
  <input type="radio" name="SET2" ng-model="SET2Selected" value="S5"> S5
  <input type="radio" name="SET2" ng-model="SET2Selected" value="S6"> S6
  </div>
  <div class="row">
  <button ng-click="submitRadioBtn()">submit</button>
  </div>
</body>

</html>