How to have a default option in Angular.js select box
For a default selection in an Angular.js select box, set your model to a default value that matches one of the options. Here's the quick-hit recipe:
The ng-model matches with an option's id in $scope.options, and voila! The first option comes up as the default selection.
Handling dynamic options with ng-init
If you have dynamic options or deal with async data, you might find ng-init helpful to set the default:
The ng-init in conjunction with || ensures the initial value is safe and sound, even when the options come late to the party (because they're on async data fetching duty).
Mastering ng-options for precise control
Track me if you can: 'track by'
To gain more control, especially when dealing with unique identifers, throw the track by clause in the ng-options:
Async data? No problem!
For asynchronously loaded data, make sure the ng-model corresponds to a real McCoy in your options. Watch out for those async bullets using $scope.$watch or initialize the ng-model in a callback.
No "?" in my selection, please!
Your select box might show an empty option (? value ?). That happens when Angular is playing Marco Polo with the selectedOption and can't find it in the options list. Cut this game short by initializing selectedOption with a real object from the options list.
Need more power? Use a custom initialization function
For more nuanced scenarios, bump up the init game with a custom JavaScript function:
This function comes handy when your default logic craves for more consideration than a starry-eyed look towards the first option.
Was this article helpful?