user1797792
user1797792

Reputation: 1189

AngularJS <select> ng-options selected value is not properly set

I have this pseudo code angularjs app. You can select a hobby for each person, save it and load it again. However when I load the data, the select boxes dont have the correct option selected. person.hobby exists and is the correct object, but it looks like ng-model isn't set correctly. Am I missing something?

<div ng-repeat="person in people">
    <p>{{ person.fullname }}</p>
    <select ng-model="person.hobby"
            ng-options="h.hobby_name group by h.category for h in hobbies">
    </select>
</div>

<script>

     //... controller...

     $http.get('/gethobbies/').succes(data) {
        hobbies = data;
     };

    $http.get('/getpeople/').succes(data) {
        people = data;
        // looks like this:  [{'fullname': 'bill gates', 'hobby': {'hobby_name': 'programming', 'category': 'computers'}, ...]
    };
</script>

Upvotes: 1

Views: 1735

Answers (1)

ivarni
ivarni

Reputation: 17878

ng-model needs to be set to the exact same object as the one in the ng-options array that you want to be selected. Angular uses object references to figure out which one should be active so having a "hobby-object" with the same "hobby_name" as one of the objects in "hobbies" is not enough. It needs to be a reference to the same object.

See documentation for select for details

Upvotes: 1

Related Questions