2

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!

Simon Bengtsson
  • 7,573
  • 3
  • 58
  • 87

1 Answers1

7

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>
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • @EdwinDalorzo Thank you. I was surprised that ng-options within a select tag don't let you use custom option values... Added another example. – Shomz Feb 02 '14 at 14:59
  • Thanks! However, my options are coming from a db so right now I'm generating them in php. I suppose I could do something like echo "var persons = json_encode($persons)"; and then do $scope.persons = persons in my ng controller. Is this how you would go about it? – Simon Bengtsson Feb 02 '14 at 15:13
  • 1
    @SimonBengtsson Yes, exactly! I wasn't sure about your input data, but if it's an exact match, that works perfectly; if not, it would require some filtering before putting it into a scope variable. I believe the sooner you place your server data into angular, the better. – Shomz Feb 02 '14 at 15:22
  • at http://jsfiddle.net/bKHh8/ when change item in sselect box clear persons data because ng-model=persons – Behnam Aug 23 '14 at 09:00
  • @بهناممحمدی Yes, it was just an example to show the names as options. By changing the model to something else, the item changing works: http://jsfiddle.net/bKHh8/8/ – Shomz Aug 23 '14 at 11:31