1

我正在使用 Angular Material,md-select并且我想创建一个空白选项,这样当您选择它时,您在选择中没有任何价值。如果我要求它,那么我希望这个选项在检查时返回 false。

这是一个演示: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>

我的情况更复杂,所以我不想要解决方法,我只想在选择空白选项时让所需的工作正常。

4

2 回答 2

1

问后问题改变了。最初不是md-select这样,所以可能有更好的方法来做到这一点。您需要做的就是将此选项添加到您的md-select

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

并从您的对象中删除该blank条目。

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}
]}

如果您使用的是常规的,这就足够了select,但是md-select考虑到 null 值来满足该required属性,因此您需要额外的工作。

在您的选择中,添加一个checkNull要运行的函数onchange

 ng-change="checkNull()"

然后将其添加到您的范围:

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

工作小提琴

于 2018-10-05T10:12:03.867 回答
1

尝试添加以下代码段:

<md-option ng-value disabled>Choose One</md-option>
于 2018-10-08T08:21:50.543 回答