AngularJS检查和获取单选按钮的值。

问题描述 投票:0回答:1

我刚刚开始学习angular,并尝试实现基本的东西。我做了3个单选按钮和相应的控制器。我想做的是检查单选按钮是否被选中,并获取该选中的值,然后将其传递给另一个控制器(可以在我做完基础知识后再做)。

这是我的代码。

 <input type="radio" name="prepay" ng-model="radioSelect" value="prepay" ng-click="selectedPaymentType(radioSelect)" required="" class="ng-untouched ng-dirty ng-valid ng-valid-required">
 <input type="radio" name="purchasepower" ng-model="radioSelect" value="purchasepower" ng-click="selectedPaymentType(radioSelect)" required="" class="ng-untouched ng-dirty ng-valid ng-valid-required">
 <input type="radio" name="lease" ng-model="radioSelect" value="lease" ng-click="selectedPaymentType(radioSelect)" required="" class="ng-untouched ng-dirty ng-valid ng-valid-required">
<!-- continue button -->
<button class="btn btn-primary btn-md" ng-click="opennext()">Continue</button>

控制器:

 $scope.opennext = function() {
}

我想的是在选择之前禁用继续按钮,为此我想使用... ...

ng-disabled="form.$invalid" 
ng-class="{gray:form.$invalid}"

或者在控制器中检查单选按钮是否没有被选中。

  if (check if radio picked) {
                      document.getElementById("btnSubmit").disabled = false;
            angular.element($('#btnSubmit')).removeClass("gray");
                     }

但我没有使用任何表单标签,所以这个方法行不通。

javascript angularjs
1个回答
1
投票

你可以通过检查if来实现禁用逻辑。radioSelect 范围变量有无设置任何值,因为最初,它将为空,直到选择任何单选按钮。

ng-disabled="!radioSelect" ng-class="{gray:!radioSelect}"

工作演示:

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
  $scope.radioSelect = ''  
});
.gray {background-color: #999;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<section ng-app="myApp" ng-controller="AppCtrl">
  <h4>Please select one option:</h4>
  <input type="radio" name="prepay" ng-model="radioSelect" value="prepay" ng-click="selectedPaymentType(radioSelect)" required> Prepay<br/>
  <input type="radio" name="purchasepower" ng-model="radioSelect" value="purchasepower" ng-click="selectedPaymentType(radioSelect)" required> Purchase Power<br/>
  <input type="radio" name="lease" ng-model="radioSelect" value="lease" ng-click="selectedPaymentType(radioSelect)" required> Lease<br/><br/>
  <!-- continue button -->
  <button class="btn btn-primary btn-md" ng-click="opennext()" ng-disabled="!radioSelect" ng-class="{gray:!radioSelect}">Continue</button><br/><br/>
  
  <div ng-if="!!radioSelect"><b>Selected option:</b> {{ radioSelect }}</div>
</section>
© www.soinside.com 2019 - 2024. All rights reserved.