-->

Angularjs how to set the default value for select

2019-07-04 16:14发布

问题:

I have the following object:

defaults = {
0 : {
    id : 10,
    value : "string 1"
    },
1 : {
    id : 22,
    value : "string 2"
    }
}

I want to iterate over this object and display it as a select box.

<select ng-model="selectedValue" ng-options="obj.id as obj.value for obj in defaults">
   <option value="">---Select option-----</option>
</select>

What I'm trying to achieve is to select 'string 2' by default. But it does not work. The problem I have is the fact the selectedValue is a string:

$scope.selectedValue = "string 2";

From what I learned from the documentation the selectedValue must be the same object. But unfortunately, it is not possible. In my case selectedValue must be a string. In other words I need to operate with the name of the option only, I don't care about id. I tried to use ng-repeat. It even works but displays an empty option and I don't think using ng-repeat is a good way to do it.

Any advice will be appreciated greatly.

回答1:

If you want the selectedValue variable to contain the value, and not the ID, then you should not use obj.id as obj.value, but obj.value as obj.value.



回答2:

Selected value should be id;

 $scope.selectedValue = 22;

See Demo

EDIT:

change template

 <select ng-model="selectedValue" >
   <option value="">---Select option-----</option>
   <option ng-selected="selectedValue == obj.value" value="{{obj.value}}" ng-repeat="obj in defaults">{{obj.value}}</option>
 </select>

see Updated Demo



回答3:

I think you misinterpreted the documentation.

Selected value should refer to a value of the same object, not be an object itself.

Thus, you can set the default value as :

$scope.selectedValue = $scope.defaults[1].value;

That way, the default value will be set - it does not matter if the value is a string or a number.



回答4:

If you are using ng-repeat with options you need to use on-last-repeat on your options tag. For example select name="repeatSelect" id="repeatSelect" ng-model="usertypes.SelectedId"

option ng-repeat="option in usertypes.AvailableOptions" value="{{option.Id}}" ng-selected="option.Id === usertypes.SelectedId" on-last-repeat>{{option.Name}}

select