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

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


You can simply use ng-init like this

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


If you want to make sure your $scope.somethingHere value doesn't get overwritten when your view initializes, you'll want to coalesce (somethingHere = somethingHere || options[0].value) the value in your ng-init like so:

<select ng-model="somethingHere"         ng-init="somethingHere = somethingHere || options[0].value"        ng-options="option.value as option.name for option in options"></select>


Try this:

HTML

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

Javascript

function Ctrl($scope) {    $scope.options = [        {          name: 'Something Cool',          value: 'something-cool-value'        },         {          name: 'Something Else',          value: 'something-else-value'        }    ];    $scope.selectedOption = $scope.options[0];}

Plunker here.

If you really want to set the value that will be bound to the model, then change the ng-options attribute to

ng-options="option.value as option.name for option in options"

and the Javascript to

...$scope.selectedOption = $scope.options[0].value;

Another Plunker here considering the above.