Home > Web Front-end > JS Tutorial > How to Set the Default Option in an AngularJS Select Box?

How to Set the Default Option in an AngularJS Select Box?

Mary-Kate Olsen
Release: 2024-11-25 06:00:14
Original
302 people have browsed it

How to Set the Default Option in an AngularJS Select Box?

Set Default Option in AngularJS Select Box

In AngularJS, select boxes can be easily initialized with a default option using various methods. Let's explore how to achieve this with different approaches:

Using ng-init

This is a straightforward way to set the default option. Simply add an ng-init directive to the select box and assign the desired default value to the model property. For example:

<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options">
</select>
Copy after login

Using Change Detection

This method utilizes AngularJS's change detection mechanism. By setting a watch on the model property and manually setting the default value if it's initially undefined, you can achieve the desired result:

<select ng-model="somethingHere" ng-options="option.name for option in options">
</select>

<div ng-controller="MyCtrl">
  $scope.$watch('somethingHere', function(newVal) {
    if (!newVal) {
      $scope.somethingHere = options[0];
    }
  });
</div>
Copy after login

Using ng-if

With ng-if, you can conditionally render an option as selected based on the value of the model property:

<select ng-model="somethingHere" ng-options="option.name for option in options">
  <option value="0" ng-if="!somethingHere">Something Cool</option>
  <option ng-repeat="option in options" value="{{option.value}}">{{option.name}}</option>
</select>
Copy after login

Using ng-selected Directive

This directive allows you to specify a condition that, when evaluated to true, will make the option selected. It can be used as follows:

<select ng-model="somethingHere" ng-options="option.name for option in options">
  <option value="0" ng-selected="!somethingHere">Something Cool</option>
  <option ng-repeat="option in options" value="{{option.value}}">{{option.name}}</option>
</select>
Copy after login

Choose the method that best suits your needs and enjoy the convenience of setting default options in your AngularJS select boxes.

The above is the detailed content of How to Set the Default Option in an AngularJS 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template