如何使用ng-options初始化一个带有对象值的select

AngularJS How to initialize a select using ng-options with an object value

本文关键字:对象 select 一个 ng-options 何使用 初始化      更新时间:2023-09-26

我想用ng-options初始化一个select字段的选择。

让我们假设我们有以下项目:

$scope.items = [{
  id: 1,
  label: 'aLabel',
  subItem: { name: 'aSubItem' }
}, {
  id: 2,
  label: 'bLabel',
  subItem: { name: 'bSubItem' }
}];

下面的html:

<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>

但是现在不是通过下面的命令选择选项:

$scope.selected = $scope.items[0];

我没有对象,只有id信息所以我喜欢这样初始化select

$scope.selected = $scope.otherRandomObject.id 

我的想法是,使用track by item.id以某种方式创建对象和id之间的关系。

如果你想要一个预先选定的值,那么你可以使用ng-selected

<select ng-options="item as item.label for item in items" ng-selected="$first"></select>

在本例中,项目数组中的第一个项目将被选中

希望我回答了你的问题