我想要一个带有md-select的空白选项,并且我希望它在需要时不进行验证 [英] I want a blank option with md-select and I want it not to validate when required

查看:94
本文介绍了我想要一个带有md-select的空白选项,并且我希望它在需要时不进行验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular Material和md-select,我想做一个空白选项,以便当您选择它时,选择中没有任何值.如果我需要它,那么我希望此选项在检查时返回false.

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.

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

推荐答案

询问后问题已更改.本来不是有关md-select的,所以可能有更好的方法.您需要做的就是将此选项添加到您的md-select:

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>

并从对象中删除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属性,因此您需要进行额外的工作.

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.

根据您的选择,添加功能checkNull以运行onchange:

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);
    }
};

工作小提琴

这篇关于我想要一个带有md-select的空白选项,并且我希望它在需要时不进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆