Mattia Pettenuzzo Mattia Pettenuzzo - 3 months ago 5
AngularJS Question

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

I have this code:


View:

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


Controller:

$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?

Answer

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];
Comments