2015-02-07 81 views
1

當對象來自服務器時,我遇到了麻煩的選擇選項。角度不會從複雜對象中選擇選擇框選項

<select class="form-control" 
      ng-hide="trip.checked1" 
      ng-model="trip.location" 
      ng-change="tripLocationChange(shift, trip)" 
      ng-options="obj as obj.text for obj in locations" required> 
    </select> 

我傳入對象是

"location":{"text":"Foo","value":"f6a62517"} 

,我填充選擇框與

$scope.locations = [{"text":"Bar","value":"f07a2bc4"},{"text":"Foo","value":"f6a62517"}] 

我認爲問題就出在這裏 ng-options="obj as obj.text for obj in locations"

任何想法可以理解

+0

顯示如何設置'$ scope.trip.location'? – dfsq 2015-02-07 18:57:04

+0

我從更大的上下文中提取了這個' shift.trips「>'也有重複的輪班。但基本上我能夠得到'

{{trip.location.text}}

'沒有任何問題 – aurimas 2015-02-07 19:03:24

回答

1

問題是即使來自服務器的對象設置爲$scope.trip.location看起來類似於$scope.locations陣列中的對象,它們也是不同的對象。與此同時,Angular會檢查對象是否平衡,以便將selectbox選項設置爲selected,並且兩個對象只有在對象爲相同對象時才相等。這不是你的情況。

在您的情況下,您將不得不通過$scope.locations數組循環,找到適當的對象並將$scope.trip設置爲找到的值。這應該適合你:

// trip object came from server 
var trip = {"location":{"text":"Foo","value":"f6a62517"}}; 

// use it to find similar object in $scope.locations array 
$scope.trip = { 
    location: $scope.locations.filter(function(location) { 
     return location.value === trip.location.value; 
    })[0] 
}; 
+0

**謝謝**讓我看看方式,讓它工作like this 'trips [y] .location = $ scope.locations.filter(function(location){ return location.value === trips [y] .location.value; })[0]' – aurimas 2015-02-07 19:22:51

+0

再次感謝... – aurimas 2015-02-07 19:38:31