2015-11-19 147 views
3

我需要一些幫助。我不能創建$scope.headline.category到一個對象,它必須保持一個字符串。 groupList必須是對象列表。我怎樣才能將下拉菜單的初始值設置爲第二項(1索引)?我可以通過控制器設置它,但是我有很多項目,似乎應該有一個更簡單的方法...也許使用ng-init?感謝您的任何幫助。使用Angular中的對象在選擇下拉菜單中設置默認值

我試過,但不起作用:

ng-init="headline.category = group.label" 

我試過了工作,但我覺得有一個更簡單的方法?

for (var a = 0; a < $scope.headlineList.length; a++) { 
    for (var b = 0; b < $scope.groupList.length; b++) { 
     if ($scope.headlineList[a].category == $scope.groupList[b].label) { 
      $scope.headlineList[a].category = $scope.groupList[b]; 
     } 
    } 
} 

$scope.headline.category = "B"; 
$scope.groupList = [ {label: "A"}, {label: "B"}, {label: "C"} ]; 

HTML

<select ng-model="headline.category" ng-options="group.label for group in groupList"></select> 

回答

1

我想你只需要在控制器中的以下內容:

app.controller('MyCtrl',function($scope){ 
     $scope.headline = { category: "B" } 
     $scope.groupList = [ {label: "A"}, {label: "B"}, {label: "C"} ]; 
    }); 

和選擇更改爲:

<select ng-model="headline.category" ng-options="group.label as group.label for group in groupList"></select> 

被設置標題中的{ category: "B" }對象的關鍵變化(這樣設置的從我猜測的某種ajax調用中)和選項開頭的group.label as來指示應用於模型的類別對象中的值。

Plunk example

+0

哦,廢話它的工作!只需添加「group.label as group.label」就可以使用! ty so much much – user1189352

+1

@ user1189352當查找值是ID-描述配對時,對於保存Id與標籤字符串也很有用。在這種情況下「group.id as group.label」。 –

0

修訂 嘗試:

<select ng-model="headline.category" ng-init="headline.category = groupList[index]" ng-options="group.label for group in groupList"></select> 

位指示:

angular.forEach($scope.groupList, function(value, key) { 
     if(value.label == $scope.headline.category){ 
      $scope.index = key; 
     } 
    }); 

PLUNKER附演示。

+0

,做的工作,但也許我沒有解釋OP以及enough.i需要的東西,其中初始指數將動態地進行設定..我不知道是否該類別將是「A」,「 B「或」C「,所以我不能像這樣不幸設置它 – user1189352

+0

也許[這個答案](http://stackoverflow.com/questions/17645620/ng-selected-not-working-in-select-element/17646636#17646636)將有所幫助。它顯示瞭如何設置控制器的初始值 – georgeawg

+0

@georgeawg檢查出來了,我想這就是我在OP中已經做的事情「我嘗試過的那些工作,但我覺得有一個更簡單的方法?」。認爲會有一些更容易,但我猜不是。 – user1189352