Reputation: 73
I have been working on trying to set the default pre-selected option for angularJS and for some reason I can't. Here is a link to the relevant Plunkr.
Here is the relevant code:
<select
ng-model="selectedOption"
ng-options="option.value as option.name for option in options">
</select>
I've tried ng-init and a bunch of different ways; I can't figure how to make the top option the preselected one.
Upvotes: 2
Views: 2320
Reputation: 14958
If what you want is to set one of the options pre-defined in options
,
in your ng-init
do something like this $scope.selectedOption = <value>
where <value>
is the value property of the object you want to be marked as selected by default. For example 1
if your first object in options
would be, {value: 1, name: "Option Number 1}
. See code below:
$scope.options = [{value:1, name: "Option 1"}, {value:2, name: "Options 2"}];
$scope.selectedOption = 1;
On the other hand, if you only want to show a predefined option indicating the user to select one option (and not one of the options in your options
)...
This is a very simple (but effective way to achieve that). See code below:
<select
ng-model="selectedOption"
ng-options="option.value as option.name for option in options">
<option value="">--Default--</option>
</select>
Upvotes: 1
Reputation: 1072
Link to updated plunkr : http://plnkr.co/edit/SkS0NqyXpnMcddu80anf?p=preview
Updating model code moved in the function and also select as
and track by
should be avoided as mentioned in the angular doc
Be careful when using select as and track by in the same expression.
Upvotes: 0
Reputation: 105439
The linked answer suggests using ng-init
. I would go with assigning default option into selectedOption
in controller or directive's link
function:
$scope.selectedOption = options[0]
I don't see a need to use another directive for this simple task.
Upvotes: 3
Reputation: 1825
just update model of the element i.e. selectedOption='yourDefaultValue'
What is the version of angular are you using? if the latest one, then you can use below code::
<select
ng-model="selectedOption" [ng-value]='yourDefaultValue'`
ng-options="option.value as option.name for option in options">
</select>
Upvotes: 0