2012-12-17 138 views
51

$指數如果我使用綁定數組的SELECT標籤下面:AngularJS - 使用在NG選項

<select ng-model="selData" ng-options="$index as d.name for d in data"> 

的OPTION標籤得到預期的增加指數值(0,1,2,... )。但是,當我從下拉菜單中選擇某個內容時,selData的值將被綁定到undefined。綁定實際上是否工作?

在另一方面,如果我做到以下幾點:

<select ng-model="selData" ng-options="d as d.name for d in data"> 

的OPTION標籤得到同樣的指數,但整個對象綁定上的改變。我不知道Angular是否支持這個功能,或者它只是一個很好的bug /副作用。

回答

20

$ index是爲ng-repeat定義的,不是選擇。我認爲這解釋了undefined。 (所以,不,這不應該起作用。)

Angular支持綁定整個對象。文檔可以更好地表明這一點,但它確實提示:「當你希望選擇模型綁定到非字符串值時,應該使用ngOptions而不是ngRepeat。」

+0

查看Harry的回答,下面提供了一個簡單的解決方法。 – gm2008

43

由於您不能使用$index,但您可以嘗試indexOf

HTML

<div ng-app ng-controller="MyCtrl"> 
    <select 
      ng-model="selectedItem" 
      ng-options="values.indexOf(selectedItem) as selectedItem for selectedItem in values"></select> 
    selectedItem: {{selectedItem}} 
</div> 

控制器

function MyCtrl($scope) { 
    $scope.values = ["Value1","Value2"]; 
    $scope.selectedItem = 0; 
} 

演示Fiddle

評論:

Array.prototype.indexOf不IE7(8)支撐

+0

也許唯一要指出的是'Array.prototype。indexOf'在IE8(和IE7)中不受支持。 – PrimosK

+0

@PrimosK謝謝你,對,加了 –

+0

謝謝@MaximShoustin這個答案解決了我的問題:) – jamseernj

178

由於陣列是非常類似於在JavaScript對象,則可以使用用於「對象的數據源」的語法。訣竅是在括號NG-選項部分:

var choices = [ 
    'One', 
    'Two', 
    'Three' 
]; 

在模板:

<select 
    ng-model="model.choice" 
    ng-options="idx as choice for (idx, choice) in choices"> 
</select> 

最後,model.choice將具有值0,1,或者2.當它爲0時,你會看到'One'; 1會顯示'Two'等,但在模型中,您只會看到索引值。

我改編了PACKT Publishing的「掌握AngularJS開發Web應用程序開發」中的信息,並在Angular reference documentation for select進行了驗證。

+5

聰明的把戲。正是我需要的,除了模型設置爲字符串而不是數字。 – manikanta

+0

非常感謝你..當這個小事情正好實現的時候,這樣的小事情會讓你想起 –

+0

甜,很聰明。所以你可以使用帶有ng-options的索引。 – Craig

4

您還可以在<option>標記中使用ng-value ='$ index'。

<select ng-model="selData"> 
<option ng-repeat="d in data track by $index" ng-value="$index"> 
    {{d.name}} 
</option> 
</select> 
+0

'ng-value'不會包含數字,只包含字符串 – Romko