javascript - AngularJS Dropdown 需要验证

标签 javascript asp.net angularjs angularjs-validation

以下是我的代码片段。我想使用 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 Require field validator DefaultValue="0"for dropdown,所以这里我的下拉列表将从服务绑定(bind),我想选择除“选择服务”之外的所有其他值。

最佳答案

您需要在下拉列表中添加一个name 属性,然后您需要添加一个required 属性,然后您可以使用myForm 引用错误.[输入名称].$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 .

关于javascript - AngularJS Dropdown 需要验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15360094/

相关文章:

javascript - 使不可见的 div 在单击时变为可见不起作用

javascript - 如何在公共(public)标题下嵌套组件

Javascript 中的 HAML 中的 Javascript

c# - 无法加载文件或程序集 'Microsoft.Practices.EnterpriseLibrary.Common' 或其依赖项之一

javascript - Angularjs 阻止页面加载并在点击时显示值

javascript - 在 chrome 扩展中加载内容脚本

c# - 从 session 中的列表中删除特定项目

asp.net - Google Chrome 的消息 "A data breach on a site or app exposed your password"是否表明我的网页存在漏洞?

javascript - 绑定(bind)到 Controller 上的原始值

javascript - jQuery deferred.always() 回调的 Angular 等价物