[英]Angular material md-select empty value validation not working
In md-select, I have added an empty md-option item and this select field is a required field. 在md-select中,我添加了一个空的md-option项,并且该选择字段是必填字段。 But Validation is not working when I selected 'Choose One' item with value as empty. 但是,当我选择“选择一个”值为空的项目时,验证不起作用。
Codepen : http://codepen.io/anon/pen/ygrJLG 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>
You can fix it with that: 您可以使用以下方法修复它:
$scope.$watch('favoriteColor', function(val)
{
if (!val) $scope.favoriteColor = null;
});
Why? 为什么? Because there is a difference between null
and undefined
: 因为null
和undefined
之间存在差异:
null = the value set to empty value null =设置为空值的值
undefined = the value has not been initialized 未定义=值尚未初始化
只需通过以下方式禁用“选择一个”选项:
<md-option ng-value disabled>Choose One</md-option>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.