【问题标题】:how to ignore 'disabled select box' when form submiting in AngularJS?在AngularJS中提交表单时如何忽略“禁用的选择框”?
【发布时间】:2017-03-16 07:15:45
【问题描述】:

当用户单击提交按钮时,将检查表单验证。如果用户选择国家“奥地利”,则禁用状态选择框。禁用的选择框不应该检查验证,否则验证将检查。我能怎么做?我尝试了下面的代码。

html
----
<div ng-app="myApp" ng-controller="myCtrl">
<form name="signup">
<div>
<p>
                <label>Please select a country</label>
                <span>
                    <select id="country" style="width:100px;" class="" ng-model="state1" ng-required="true">
                          <option ng-repeat="(key,country) in countries"  value="{{key}}">{{country[0]}}</option>
                    </select>
                </span>
            </p>
            <p>
                <label>States<span class="red">*</span></label>
                <span>
                <select id="state" ng-disabled="!states[state1].length" style="width:100px;" name="stateName"  ng-model="cities" ng-required="true">
                     <option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
                </select>
                </span>
                <p class="red" ng-show="signup.stateName.$error.required">{{stateMsg}}</p>
</div>
 <button ng-click="val(signup.$valid);">
 submit
 </button>
 </form>
</div>

script
-----
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.val = function(x){
 if(x===false){
 $scope.stateMsg = "cities is rquried"
 }
 else{
  alert("form valid");
 }
}
    $scope.states =  {
     "IN":[
       "Delhi",
       "Goa",
       "Gujarat",
       "Himachal Pradesh",
     ]
   };
   $scope.countries =  {
      IN: ["India"],
       ZA: ["South Africa"],
       AT: ["Austria"]
     }
     $scope.state1 = Object.keys($scope.countries)[0];
    $scope.lastName = "Doe";
});

jsfiddle
-------
https://jsfiddle.net/Lc3n55d2/23/

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    替换

    ng-required="true"
    

    通过

    ng-required="states[state1].length"
    

    【讨论】:

      【解决方案2】:

      只需将检查从 ng-required="true" 添加到 ng-required="states[state1].length > 0"

      <select id="state" ng-disabled="!states[state1].length" style="width:100px;" name="stateName"  ng-model="cities" ng-required="states[state1].length > 0">
      

      工作 jsfiddle:https://jsfiddle.net/Lc3n55d2/24/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-03
        • 1970-01-01
        • 2021-10-08
        • 2016-08-05
        • 1970-01-01
        • 2011-07-12
        • 1970-01-01
        • 2013-10-14
        相关资源
        最近更新 更多