简体   繁体   中英

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

I would like to initialize a selection of a select field with ng-options .

Lets assume we've got the following items:

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

The following html:

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

But now instead of selecting the option by the following command:

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

I do not have the object, I have only the information of the id so I like to initialize the select by something like that:

$scope.selected = $scope.otherRandomObject.id 

My thought was that using track by item.id is somehow creating the relation between object and the id.

If you want to have a pre-selected value, then you can use ng-selected

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

In this case, the first item in your item array would be selected

Hope i answered your question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM