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>
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.
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.
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 .
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With