Search code examples
javascriptangularjsng-optionsangularjs-ng-options

ngOptions with array of objects does not set the first value


I have an array of objects with the following format:

[
  {key: 'SC', name: 'Santa Catarina'},
  {key: 'SP', name: 'São Paulo'},
  {key: 'RJ', name: 'Rio de Janeiro'}
]

And I want to use select and ng-options to show those values:

<select ng-model="vm.state"
    ng-options="state.name for state in vm.states">
</select>

However, if vm.state already has a value, the select does not start with it selected. Does anyone know how to make it happen?

Fiddle demonstrating the problem.

Thanks! :)


Solution

  • You could use track by in this case, where you are retrieving selected object from some ajax call.

    <select ng-model="vm.state"
          ng-options="state.name for state in vm.states track by state.key">
    </select>
    

    JSFiddle

    NOTE: track by will not work if you are using select as in ng-options expression.`