简体   繁体   中英

select with ng-options, how to initialize with a field already selected

I have this code:

<select 
        ng-model="filterList" 
        ng-options="data.name for data in filter_options">
</select>

$scope.filter_options = [
        {id: 1, name: 'User'},
        {id: 2, name: 'Option 2'},
        {id: 3, name: 'Option 3'}
];

When I first enter the controller, in the select there is nothing and the user MUST have to select something.
I tried to pass

$scope.filterList = {id: 1, name: 'User'};

but the select field remains empty.

I want that the option "User" is already select when I enter the controller. Is that duable?

You could use track by in such cases, where it tracking changes based on data.id .

<select ng-model="filterList" 
   ng-options="data.name for data in filter_options track by data.id">
</select>

NOTE: track by would harm if you are using with select as

Demo Plunkr


The other way is you could select you could do

$scope.filterList = $scope.filter_options[0];

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