In Angular.js, setting a default option in a select box is a common requirement. By default, select boxes display the first option as selected. However, developers may want to specify a different option as the default based on business logic or user preferences.
Consider the following code snippet:
<select ng-model="somethingHere" ng-options="option.value as option.name for option in options"> </select>
With the following data:
options = [{ name: 'Something Cool', value: 'something-cool-value' }, { name: 'Something Else', value: 'something-else-value' }];
This code will produce a select box with the first option ("Something Cool") selected by default. To change this behavior, you can use Angular.js' ng-init directive. ng-init allows you to initialize a scope variable on the element it's applied to.
<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"> </select>
By setting somethingHere to the first element of the options array in the ng-init directive, you can force the select box to display the first option as selected by default.
The above is the detailed content of How to Set a Default Option in an Angular.js Select Box?. For more information, please follow other related articles on the PHP Chinese website!