2015-10-27 91 views
1

我在這裏失去了一些東西很簡單,我在我的控制器的陣列如下AngularJS選擇標記驗證

$scope.roles = [ 
     {id: 0, label: 'Choose a Role'}, 
     {id: 1, label: 'Administrator'}, 
     {id: 2, label: 'Super User'} 
    ]; 

而以下是我在視圖中選擇標籤

<select ng-options="role.id as role.label for role in roles" ng-model="myForm.role" ng-required="true"> 
</select> 

哪有我驗證用戶是否選擇了AdministratorSuper User而不是Choose a Role

+0

我添加了一個小提琴我的回答讓您可以有一個工作的例子。請讓我知道它是否符合您的需求。 – IggY

回答

0

EDIT2:https://jsfiddle.net/3kL9rmp8/

編輯:我給你做一個小提琴:https://jsfiddle.net/fgpg9zvn/

你可以這樣添加一個選項:

<select ng-options="role.id as role.label for role in roles" 
     ng-model="myForm.role" 
     ng-required="true"> 
     <option value="" disabled selected style="display: none;"> Chose a role </option> 
</select> 
+0

其實它幾乎在那裏,除了選擇一個角色的值必須是'0',我也必須將表單設置爲無效 – user3052526

+0

@ user3052526看看我的Edit2小提琴 - >如果沒有,則表單被設置爲無效值被選擇(請參閱消息),但我不明白爲什麼您要「選擇角色」消息具有值,因爲選擇此值時無法提交表單? – IggY

+0

它從後端api悲傷的要求。現在看看 – user3052526

0

從HTML,你可以使用:

<div ng-if="myForm.role == 'Chose a role"> 
Your code when 'Chose a role; 
</div> 

JS:

if ($scope.myForm.role == 'Chose a role) { 
    Your code here 
} 
+0

但是,在這種情況下'myForm'將如何失效? – user3052526

0

試試這個簡潔明瞭的解決方案。 使用此HTML有選擇元素。

HTML:

<select ng-model="myForm.role" 
     ng-options="role.id as role.label for role in roles" 
     ng-change="fillTheDDL(role.id, role.label)"> 

    <option value="">Chose a role</option> 

</select> 

使用此JS來獲得所需的功能。

JS:

$scope.fillTheDDL= function (ID, Label) { 
    if (Label != "Choose a Role") { 
    // Your favorite code here  
    } 
    else { 
     // You don't wanna use it 
    } 
};