I want a blank option with md-select and I want it not to validate when required

后端 未结 2 1348
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 22:35

I\'m using Angular Material and md-select and I would like to make a blank option such that when you select it, you have no value in the select. In the case that I

相关标签:
2条回答
  • 2021-01-26 23:09

    Try adding the following code segment:

    <md-option ng-value disabled>Choose One</md-option>
    
    0 讨论(0)
  • 2021-01-26 23:18

    QUESTION CHANGED AFTER ASKING. Not originally about md-select so there may be a better way to do this. All you need to do is add this option to your md-select:

    <md-option value=""></md-option>
    

    And remove the blank entry from your object.

    HTML

    <select ng-model="selectedValue2" required >
        <option value=""></option>
        <option ng-repeat="option in options['id'] | orderBy: 'id'" ng-value="option.value">{{option.name}}</option>
    </select>
    

    JavaScript

    $scope.options = {id : [
        {name : 'World', value : 'World', id:3},
        {name : 'qweqwe', value : 'qweqwe', id:1},
        {name : 'rwerasdf', value : 'rwerasdf', id:2}
    ]}
    

    This would be enough if you were using a regular select, but md-select considers the null value to satisfy the required attribute so you need extra work.

    In your select, add a function checkNull to run onchange:

     ng-change="checkNull()"
    

    Then add it to your scope:

    $scope.checkNull = function(){
        if(typeof $scope.selectedValue2 === "undefined"){
            $scope.myform.myselect.$setValidity("required", false);
        }
    };
    

    Working Fiddle

    0 讨论(0)
提交回复
热议问题