简体   繁体   中英

Angular ng-options preselect a value using an option datasource

I have an object like so:

$scope.properties = {
    1: 'Option A',
    2: 'Option B',
    3: 'Option C'
};

And an ng-model variable like so:

$scope.selectedValue = 2;

And some markup like so:

<select ng-options="key as value for (key, value) in ctl.properties" 
        ng-model="ctl.selectedValue">
</select>

But there seems to be absolutely no way of pre-selecting a value from that dropdown by its value. I've managed to get it to work if I set the selected value like this:

$scope.selectedValue = 'Option B';

How on earth do I get the <select> to pre-select using the option value (the key of the object) not the actual option text.

Please note, I'm not using an array of objects like mostly every article I've found uses. I've just got an object. I also don't want to change it to an array of objects. There must be a way to do this.

Many Thanks.

The dropdown needs a string key instead of a numeric one:

$scope.selectedValue = '2';

Here is a codepen as an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM