Angular JS - get selected text of a select control

devC picture devC · Sep 21, 2014 · Viewed 28.6k times · Source

I've followed the following link to solve the issue but it didn't work: How to get option text value using AngularJS?

I have a dropdown that contains a set of servers. when i select a value from the dropdown, I want the selected value to display in a separate div. Here is what I have done:

Select control:

 <select name="source" class="form-control input-sm"
                        ng-model="filterOptions.hostId"
                        ng-options="s.id as s.hostName for s in physicalServerList"
                        ng-style="{'width':'100%'}">
                </select>

Displaying selected text:

<span class="pull-left">Source: {{ filterOptions.hostId.hostName }}</span>

However, this does not display the selected text. What am I doing wrong?

Answer

PSL picture PSL · Sep 21, 2014

It does not display selected text because your model will have the id of the selected item because of the usage of s.id as s.hostName (select as label syntax) in the ng-options. Just remove the select as part from the syntax, have the ng-model hold the selected object's reference itself instead of just the id.

So your ng-option:-

ng-model="filterOptions.host"
ng-options="s.hostName for s in physicalServerList track by s.id"

and your model will be the selected object instead of just the id of the selected item

<span class="pull-left">Source: {{ filterOptions.host.hostName }}</span>

Plnkr