aurimas
aurimas

Reputation: 77

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"

any thoughts will be appreciated

Upvotes: 1

Views: 70

Answers (1)

dfsq
dfsq

Reputation: 193261

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

Upvotes: 1

Related Questions