在一个单选按钮上禁用所需属性

时间:2015-06-19 17:15:56

标签: javascript jquery html angularjs twitter-bootstrap

我在bootstrap模式中有3个单选按钮,我只需要其中2个才能提交表单。我创建了一个使用jQuery实现的requiredCheck()函数,所以我宁愿不使用它。使用AngularJS时,为一个单选按钮禁用所需属性的最佳方法是什么?

HTML

<form name="jawn">
      <div class="modal-header">
        <h3 class="modal-title">Jawn</h3>
      </div><!-- /modal-header -->
      <div class="modal-body">
        <ul>
          <li ng-repeat="item in items">
            <label for="optionsRadios">
                <input type="radio" ng-model="$parent.data.status" name="optionsRadios" ng-value="item.id" required/ ng-click="requiredCheck()"> {{item.name}}
            </label>
          </li>
        </ul>
        <h4>Comment</h4>
        <textarea ng-class="{error: thing.comment.$dirty && thing.comment.$invalid}" type="text" rows="3" cols="64" ng-model="data.comment" ng-minlength="4" ng-required></textarea>
        <span class="error" ng-show="thing.comment.$error.required">required</span>
      </div><!-- /modal-body-->
      <div class="modal-footer">
        <button type="submit" class="btn btn-warning" ng-click="ok()" ng-disabled="thing.$invalid">Part Jawn</button>
        <button type="button" ng-click="cancel()" class="btn btn-default">Cancel</button>
      </div>
    </form>

的JavaScript

angular.module('app')
.controller('ModalController', function($scope, $modalInstance, $timeout) {
  'use strict';

  $scope.item = 0;

  $scope.items = [
    "Zero": 0,
    "Uno": 1,
    "Dos": 2
  ];

  $scope.requiredCheck = function () {
    var $btnWarning = $('.btn-warning');
    var $textarea = $('textarea');
    $timeout(function() {
      if($scope.data.status === item.Dos) {
        $btnWarning.removeAttr('disabled');
        $textarea.removeAttr('required');
      } else if ($scope.data.status === 3) {
        $btnWarning.prop('disabled',true);
        $textarea.prop('required', true);
      } else if ($scope.data.status === 3) {
        $btnWarning.prop('disabled',true);
        $textarea.prop('required', true);
      }
    },100);
  };

  $scope.ok = function () {

  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
    $modalInstance.close();
  };

});

1 个答案:

答案 0 :(得分:1)

您应该使用方法。正如您已从控制器中指定ngRequired设置true / false一样。

来自DOCs

  

ngRequired:如果设置为true,则设置必需属性

HTML

<textarea ng-model="data.comment" ng-required="textRequired"></textarea>

脚本

$scope.requiredCheck = function () {
    if(condition){
        $scope.textRequired = false;
    }else{
        $scope.textRequired = true;
    }       
};

注意:我简化了答案