Explain Codes LogoExplain Codes Logo

How to have a default option in Angular.js select box

javascript
angularjs
select-box
ng-init
Alex KataevbyAlex Kataev·Dec 24, 2024
TLDR

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:

$scope.selectedOption = $scope.options[0]; // First option is now default (fast and furious!) $scope.options = [ { id: 'option1', name: 'First Option' }, // Insert your cast of options here... ];
<select ng-model="selectedOption" ng-options="option.name for option in options track by option.id"></select>

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:

<select ng-model="selectedOption" ng-init="selectedOption = selectedOption || options[0]" ng-options="option.name for option in options track by option.id"></select>

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:

<select ng-model="selectedOption" ng-options="option.id as option.name for option in options track by option.id"></select>

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:

$scope.setDefaultOption = function(options) { // If nothing's cooking, return null. Else, first option is the daily special! return options.length > 0 ? options[0] : null; }; $scope.selectedOption = $scope.setDefaultOption($scope.options);

This function comes handy when your default logic craves for more consideration than a starry-eyed look towards the first option.