2017-02-16 92 views
0

在md-select中,我添加了一個空的md選項項目,並且此選擇字段是必填字段。但是當我選擇'選擇一個'項目時,驗證不起作用,其值爲空。角度材質md-select空值驗證不起作用

Codepen:http://codepen.io/anon/pen/ygrJLG

<div ng-controller="AppCtrl" ng-cloak="" layout="column" layout-align="center center" layout-padding="" class="selectdemoValidations" ng-app="MyApp"> 
    <form name="myForm"> 

    <div layout="row" layout-align="start" flex=""> 
     <md-input-container flex> 
     <label>Favorite Color</label> 
     <md-select name="favoriteColor" ng-model="favoriteColor" required="" > 
      <md-option value=''>Choose One</md-option> 
      <md-option ng-value=color ng-repeat="color in colors">{{color}}</md-option>   
     </md-select> 
     <div class="errors" ng-messages="myForm.favoriteColor.$error"> 
      <div ng-message="required">Required</div> 
     </div> 
     </md-input-container> 
    </div> 

    <div layout="row" layout-align="start"> 
     <md-checkbox ng-model="myForm.$invalid" disabled="">Form Invalid</md-checkbox> 
     <md-checkbox ng-model="myForm.$dirty" disabled="">Form Dirty</md-checkbox> 
     <md-checkbox ng-model="myForm.$submitted" disabled="">Form Submitted</md-checkbox> 
     <md-checkbox ng-model="myForm.favoriteColor.$touched" disabled="">Select Touched</md-checkbox> 
    </div> 

    <div layout="row" layout-align="end" flex=""> 
     Selected Color is {{favoriteColor}} 
     <md-button ng-click="clearValue()" ng-disabled="!favoriteColor">Clear</md-button> 
     <md-button ng-click="save()" class="md-primary">Save</md-button> 
    </div> 
    </form> 
</div> 

回答

1

可以與修復:

$scope.$watch('favoriteColor', function(val) 
{ 
    if (!val) $scope.favoriteColor = null; 
}); 

爲什麼?因爲有nullundefined之間的差異:

空=的值設置爲空值

未定義=值尚未初始化

0

只是把「選一」選項可以禁用:

<md-option ng-value disabled>Choose One</md-option> 
+0

我應該有允許用戶選擇「二選一」,然後顯示錯誤驗證消息。 – Rookie