Search code examples
angularjsangularjs-ng-repeatng-options

Hardcoded values in NG-OPTIONS with dynamic values from NG-REPEAT


Let's say we have this data and it's being returned by an API

$scope.arrayOfStudentObjects = [
    { name : 'Ashley', gender : 'female' },
    { name : 'Tom', gender : 'male' },
    { name : 'Scott', gender : 'male' }
];

Then the values that we put in < select > are in a scope

$scope.gender = [ { type : 'male' }, { type : 'female' } ];

Now we want to display the values and correctly set the selection for the gender in the select dropdown

<tr ng-repeat="student in arrayOfStudentObjects track by $index">
    <select ng-model="student.gender" ng-options="sex.type for sex in gender"></select>
</tr>

However, I'm not sure why it's not displaying/selecting the proper gender for that student. Please see Plunker. http://plnkr.co/edit/o0Wt2Qg8BFXmeeMqFBIE?p=preview


Solution

  • change your <select...> to

     <select ng-model="student.gender" ng-options="sex.type as sex.type for sex in gender"></select>
    

    otherwise the value it compares to is the full object.

    forked plunk:

    http://plnkr.co/edit/azBhpIEUkybXmQWliMOR?p=preview