tpsilva tpsilva - 1 year ago 69
Javascript Question

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
to show those values:

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

However, if
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! :)

Answer Source

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=" for state in vm.states track by state.key">


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download