AngularJS Dropdown 需要验证 [英] AngularJS Dropdown required validation

查看:24
本文介绍了AngularJS Dropdown 需要验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码片段.我想使用 angular 验证我的下拉列表.

Following is my code snippet. I want to validate my dropdown using angular.

<td align="left" width="52%"> 
  <span class="requiredSmall">*</span> 
    <select class="Sitedropdown" style="width: 220px;" 
            ng-model="selectedSpecimen().serviceID" 
            ng-options="service.ServiceID as service.ServiceName for service in services"> 
         <option value="" ng-selected="selected">Select Service</option> 
   </select> 
</td>

有效手段:

有效值可以是选择服务"以外的任何值,这是我的默认值.像其他 ASP.net 一样需要字段验证器 DefaultValue="0" 用于下拉列表,所以这里我的下拉列表将从服务中绑定,我想选择除选择服务"之外的所有其他值.

推荐答案

你需要在下拉列表中添加一个name属性,然后你需要添加一个required属性,然后您可以使用 myForm.[input name].$error.required 引用错误:

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

这是一个有效的 plunker.

这篇关于AngularJS Dropdown 需要验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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