在md-select中,我添加了一个空的md-option项,此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>
答案 0 :(得分:1)
你可以用它修复它:
$scope.$watch('favoriteColor', function(val)
{
if (!val) $scope.favoriteColor = null;
});
为什么呢?因为null
和undefined
之间存在差异:
null =设置为空值的值
undefined =该值尚未初始化
答案 1 :(得分:0)
只需禁用“选择一个”选项:
<md-option ng-value disabled>Choose One</md-option>