简体   繁体   English

使用对象符号获取选定的ng-option的标签

[英]Get the label of selected ng-option using object notation

Given an object: 给定一个对象:

obj = {
  foo: 1,
  bar: 2
}

I create an ng-option using the object datasource notation: 我使用对象数据源符号创建ng-option

<select ng-model="selection" ng-options="key for (key, value) in obj"></select>

At this point the user will see a dropdown with the values foo and bar . 此时,用户将看到一个包含值foobar的下拉列表。 When they select an option the value of selection is change to 1 or 2 respectively. 当他们选择一个选项的值selection为改变为12分别。

But how can I go back and figure out what the currently selected key/label is? 但是,如何返回以找出当前选择的键/标签是什么?

To determine and compare the key's value in your statement, you simply need to add the select clause to your ng-options expression. 要确定和比较语句中键的值 ,只需要将select子句添加到ng-options表达式中。

<select ng-model="selection" ng-options="key as key for (key, value) in obj"></select>

This will set selection to foo or bar and not 1 or 2 and you can make your determination from there. 这会将selection设置为foobar而不是12 ,您可以从那里进行确定。

From Angular Docs 从Angular Docs

select as label for (key , value) in object select作为对象中(key,value)的label

select : The result of this expression will be bound to the model of the parent <select> element. select :此表达式的结果将绑定到父<select>元素的模型。 If not specified, select expression will default to value. 如果未指定,则选择表达式将默认为value。

Update : 更新

In order to see both key and value, you can create a new object as your select . 为了同时看到键和值,您可以创建一个新对象作为select Check out this Plunkr 看看这个Plunkr

<select ng-model="selection" ng-options="{key:key, value:value} as key for (key, value) in obj"></select>

<span>{{selection.key}}</span>
<span>{{selection.value}}</span>

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

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