2017-03-16 52 views
0

当用户点击提交按钮时,表单验证会检查,如果你用户选择国家'奥地利',状态选择框被禁用,禁用选择框不应该检查验证,其他明智的验证将检查,我怎么办,我尝试了以下代码。如何在anguarjs中提交表单时忽略“禁用选择框”?

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/ 

回答

0

替换

ng-required="true" 

通过

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

距离NG-需要= “true” 以NG-需要=添加检查 “状态[状态1]。长度> 0”

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

Working jsfiddle:https://jsfiddle.net/Lc3n55d2/24/