简体   繁体   English

Angular ng-options 使用选项数据源预选一个值

[英]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:还有一个像这样的ng-model变量:

$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.我到底如何让<select>使用选项值(对象的键)而不是实际的选项文本进行预选择。

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.这里以codepen为例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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