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

人盡茶涼 提交于 2019-12-02 09:15:47

问题


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 make it required, then I would like this option returning false at the check.

Here's a demo: https://plnkr.co/edit/FZ8xt5ZCRJY3fFMh3fFU?p=preview

<html>
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</ript>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js" data-semver="1.2.19"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form>
      <select ng-model="selectedValue2" required >
        <option ng-repeat="option in options['id'] | orderBy: 'id'" ng-value="option.value">{{option.name}}</option>
      </select>
      <button type="submit">Submit</button>
    </form>
  </body>  
</html>

My situation is more complex, so I don't want a workaround, I just would like a way to make the required working when I select the blank option.


回答1:


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




回答2:


Try adding the following code segment:

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


来源:https://stackoverflow.com/questions/52662986/i-want-a-blank-option-with-md-select-and-i-want-it-not-to-validate-when-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!