带有对象数组的 ngOptions 不设置第一个值

ngOptions with array of objects does not set the first value

我有一个对象数组,格式如下:

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

我想使用 selectng-options 来显示这些值:

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

但是,如果 vm.state 已经有一个值,则 select 不会以它 selected 开头。有谁知道如何实现它?

Fiddle demonstrating the problem.

谢谢! :)

要自己设置,类似

$scope.states=[...]
$scope.state=$scope.states[0]

首先你必须自己设置它,因为 vm.state 将从你的 vm.state 中获取值。你可以使用 ng-init 来设置它。

  <select ng-model="vm.state"
        ng-options="state.name for state in vm.states" ng-init="vm.state = $scope.states[0]">
    </select>

在这种情况下,您可以使用 track by,从某些 ajax 调用中检索选定的对象。

<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.`