I have searched Google and can\'t find anything on this.
I have this code.
I would set the model in the controller. Then the select will default to that value. Ex: html:
<select ng-options="..." ng-model="selectedItem">
Angular controller (using resource):
myResource.items(function(items){
$scope.items=items;
if(items.length>0){
$scope.selectedItem= items[0];
//if you want the first. Could be from config whatever
}
});
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>
Only one answer by Srivathsa Harish Venkataramana mentioned track by
which is indeed a solution for this!
Here is an example along with Plunker (link below) of how to use track by
in select ng-options
:
<select ng-model="selectedCity"
ng-options="city as city.name for city in cities track by city.id">
<option value="">-- Select City --</option>
</select>
If selectedCity
is defined on angular scope, and it has id
property with the same value as any id
of any city
on the cities
list, it'll be auto selected on load.
Here is Plunker for this: http://plnkr.co/edit/1EVs7R20pCffewrG0EmI?p=preview
See source documentation for more details: https://code.angularjs.org/1.3.15/docs/api/ng/directive/select
In my case since the default varies from case to case in the form. I add a custom attribute in the select tag.
<select setSeletected="{{data.value}}">
<option value="value1"> value1....
<option value="value2"> value2....
......
in the directives I created a script that checks the value and when angular fills it in sets the option with that value to selected.
.directive('setSelected', function(){
restrict: 'A',
link: (scope, element, attrs){
function setSel=(){
//test if the value is defined if not try again if so run the command
if (typeof attrs.setSelected=='undefined'){
window.setTimeout( function(){setSel()},300)
}else{
element.find('[value="'+attrs.setSelected+'"]').prop('selected',true);
}
}
}
setSel()
})
just translated this from coffescript on the fly at least the jist of it is correct if not the hole thing.
It's not the simplest way but get it done when the value varies
If you are using ng-options
to render you drop down than option
having same value as of ng-modal is default selected.
Consider the example:
<select ng-options="list.key as list.name for list in lists track by list.id" ng-model="selectedItem">
So option having same value of list.key
and selectedItem
, is default selected.