简体   繁体   English

角度不会从复杂对象中选择选择框选项

[英]angular doesn't select selectbox option from complex object

I have a trouble selecting option when Object comes from server. 当对象来自服务器时,我在选择选项时遇到麻烦。

    <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> 

my incoming object is 我的传入对象是

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

and I populate selectBox with 我用

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

I believe the problem lies in here ng-options="obj as obj.text for obj in locations" 我相信问题出在这里ng-options="obj as obj.text for obj in locations"

any thoughts will be appreciated 任何想法将不胜感激

The problem is that even though the object that comes from server which you set as $scope.trip.location looks similar to the one in $scope.locations array, they are different objects. 问题是,即使来自服务器的对象(您设置为$scope.trip.location看起来类似于$scope.locations数组中的对象,但它们是不同的对象。 At the same time, Angular checks for object equility in order to set selectbox option as selected, and two object are equal only if the are the same object. 同时,Angular检查对象是否相等,以便将selectbox选项设置为被选中,并且两个对象只有在相同对象时才相等。 This is not your case. 这不是你的情况。

In your case you will have to loop though $scope.locations array, find proper object and set $scope.trip to found value. 在您的情况下,您将不得不遍历$scope.locations数组,找到合适的对象并将$scope.trip设置为找到的值。 This should work for you: 这应该为您工作:

// 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]
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM