2013-03-12 70 views
57

以下是我的代碼片段。我想用角度來驗證我的下拉菜單。 AngularJS下拉需要驗證

<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」,所以這裏我的下拉菜單將被綁定到服務上,並且我希望選擇除「選擇服務」以外的所有其他值。

回答

113

您需要添加一個「名稱」屬性的下拉列表中,那麼你需要添加一個required屬性,然後你可以使用myForm.[input name].$error.required引用錯誤:

HTML:

<form name="myForm" ng-controller="Ctrl"> 

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

控制器:

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

這是一個工作plunker

+7

應該指出的是,選擇需要ng-model才能正常工作 – phikes 2013-08-26 10:21:26

+3

正確,ngOptions需要ngModel。 – Stewie 2013-08-26 11:38:32

+0

這個例子非常有用。謝謝。 – ddagsan 2016-06-10 15:26:51