61

以下是我的代码片段。我想使用 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",所以这里我的下拉列表将从服务中绑定,我想选择除“选择服务”之外的所有其他值。

4

1 回答 1

119

您需要在name下拉列表中添加一个属性,然后您需要添加一个required属性,然后您可以使用以下命令引用错误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');
    };
        }

这是一个工作的笨蛋

于 2013-03-12T14:09:38.640 回答