Get the selected text (not value) of select element in angular

Simon Bengtsson picture Simon Bengtsson · Feb 2, 2014 · Viewed 16k times · Source

For example I would like to do something like this:

<select ng-model="persons">
  <option value="person1">Anna Smith</option>
  <option value="person2">Karl Pettersson</option>
  <option value="person3">Ylvis Russo</option>
</select>
<p ng-view="persons"><p>

And having the view display each name when selected in the dropdown rather than it's value. Is it possible?

I tried watching the model and assigning a new model the text value with jQuery. However it ended up being complicated so if that's the best way to do it, I small example would be awesome!

Answer

Shomz picture Shomz · Feb 2, 2014

You just need to define your persons object and then you can do whatever you want with it. There are many ways to do it... Here's an example:

HTML

<select ng-model="persons"
    ng-options="p as p.label for p in persons">
</select>

<p ng-repeat="p in persons">
    {{p.value}}: {{p.label}}
</p>

JS

$scope.persons = [
    { value: 'person1', label: 'Anna Smith' },
    { value: 'person2', label: 'Karl Pettersson' },
    { value: 'person3', label: 'Ylvis Russo' }
];

Here is a jsfiddle: http://jsfiddle.net/bKHh8/

UPDATE

Here it is with option tags which don't use angular indices for values (this is exactly what answers your question): http://jsfiddle.net/bKHh8/1/

<select>
     <option ng-repeat="p in persons" value="{{p.value}}">{{p.name}}</option>
</select>