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>
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>
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>
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>
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!