Mattia Pettenuzzo Mattia Pettenuzzo - 1 year ago 61
AngularJS Question

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

I have this code:


ng-options=" for data in filter_options">


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

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

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

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download