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>
You can simply use ng-init like this
Using
select
withngOptions
and setting a default value:See the ngOptions documentation for more
ngOptions
usage examples.plnkr.co
Official documentation about HTML
SELECT
element with angular data-binding.Binding
select
to a non-string value viangModel
parsing / formatting:plnkr.co
Other example:
jsfiddle
If you have some thing instead of just init the date part, you can use
ng-init()
by declare it in your controller, and use it in the top of your HTML. This function will work like a constructor for your controller, and you can initiate your variables there.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:I needed the default “Please Select” to be unselectable. I also needed to be able to conditionally set a default selected option.
I achieved this the following simplistic way: JS code: // Flip these 2 to test selected default or no default with default “Please Select” text //$scope.defaultOption = 0; $scope.defaultOption = { key: '3', value: 'Option 3' };
HTML:
I hope this helps someone else that has similar requirements.
The "Please Select" was accomplished through Joffrey Outtier's answer here.
The Best and Simplest way(Updated)
Explained here https://stackoverflow.com/a/37962911/5902146