2015-02-07 57 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