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:

<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. When they select an option the value of selection is change to 1 or 2 respectively.

But how can I go back and figure out what the currently selected key/label is?

Upvotes: 1

Views: 1160

Answers (1)

jcc
jcc

Reputation: 1147

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-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.

From Angular Docs

select as label for (key , value) in object

select: The result of this expression will be bound to the model of the parent <select> element. If not specified, select expression will default to value.

Update:

In order to see both key and value, you can create a new object as your select. Check out this 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>

Upvotes: 2

Related Questions