Home > Web Front-end > JS Tutorial > How to Set a Default Option in an Angular.js Select Box?

How to Set a Default Option in an Angular.js Select Box?

DDD
Release: 2024-12-01 20:09:13
Original
933 people have browsed it

How to Set a Default Option in an Angular.js Select Box?

Setting a Default Option in Angular.js Select Box

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>
Copy after login

With the following data:

options = [{
   name: 'Something Cool',
   value: 'something-cool-value'
}, {
   name: 'Something Else',
   value: 'something-else-value'
}];
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template