Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have searched Google and can't find anything on this.

I have this code.

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

With some data like this

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

And the output is something like this.

<select ng-model="somethingHere"           ng-options="option.value as option.name for option in options"          class="ng-pristine ng-valid">      <option value="?" selected="selected"></option>     <option value="0">Something Cool</option>     <option value="1">Something Else</option> </select> 

How is it possible to set the first option in the data as the default value so you would get a result like this.

<select ng-model="somethingHere" ....>     <option value="0" selected="selected">Something Cool</option>     <option value="1">Something Else</option> </select> 
like image 437
iConnor Avatar asked Aug 12 '13 18:08

iConnor


People also ask

How do I set the default value in select?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How do I set default selected value in ng-options?

In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.

What is Ng select in AngularJS?

AngularJS ng-selected Directive The ng-selected directive sets the selected attribute of an <option> element in a <select> list. The option will be selected if the expression inside the ng-selected attribute returns true. The ng-selected directive is necessary to be able to shift the value between true and false .

What is ngInit?

The ngInit directive allows you to evaluate an expression in the current scope. This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit : aliasing special properties of ngRepeat , as seen in the demo below.


1 Answers

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> 
like image 75
zs2020 Avatar answered Sep 28 '22 04:09

zs2020