Search code examples
javascriptangularjsng-options

angularjs ng-option blank option instead preselected


I'm having a problem with display a preselected value as the selected option in my select element. Here goes the code

<select ng-model="data.company" ng-options="company as company.name for company in companies"></select>


$scope.companies =[{
    id:1,
    name:"Company 1"
},
{
    id:2,
    name:"Company 2"
}];

$scope.data = {
    company:{
        id:2,
        name:"Company 2"
    }
}

the problem is that when i enter in the section the select gives me a blank option as default insted of showing me "Company 2". What im i doing wrong?


Solution

  • You need to use track by in this case, as you are assigning object value to the ng-model directly. In this case what happens is, when you bind object directly to data.company(ng-model) track by expression checks company.id in that ng-model with the each companies element id. If any one gets match it pre-select that input.

    Markup

    <select ng-model="data.company" 
       ng-options="company as company.name for company in companies track by company.id">
    </select>
    

    Demo Plunkr