0

I have an array of Objects, eg:

[Object { id="121", name="Planes"}, Object { id="212", name="Buses"}, Object { id="210", name="Cars"}, .... ]

I want this to appear in a select such as:

<select....>
<option value="121"...>Planes</option>
<option value="212"...>Buses</option>
<option value="210"...>Cars</option>
</select>

But if I use the following code:

 <select.... ng-options="category.id as category.name for category in categories" .....

I get the following (the values are wrong):

<select....>
<option value="1"...>Planes</option>
<option value="2"...>Buses</option>
<option value="3"...>Cars</option>
</select>

How can I solve this?

Thanks

Martin
  • 795
  • 1
  • 12
  • 31

3 Answers3

2

Angular uses numeric values for options values in selects, but you can follow up on your select value using ng-model.

You can try (depending on the Angular version) using track by to get the correct value into select. track by category.id in your case probably.

Check this question/answer also.

EDIT: this question is pretty much the same also. Someone posted a fiddle for you below, so I won't do it now..

Community
  • 1
  • 1
trainoasis
  • 6,419
  • 12
  • 51
  • 82
1

Use the track by option within the ng-options directive

<select ng-options="category as category.name for category in categories track by category.id" ng-model="category"></select>

I made a fiddle for you

eras0r
  • 36
  • 4
  • Thanks, this worked perfectly. Instead of having "category.id as category.name..." just changed it to "category as category.name..." and it worked. Thanks so much. – Martin Jul 29 '15 at 23:42
0

Values in the rendered <select> might be incorrect, but that does not matter, because the ng-model value will be the id of selected category.

see: https://jsfiddle.net/prappjt3/2/

Jerguš Lejko
  • 610
  • 4
  • 25
  • Thanks, that is very useful and has helped my understanding. I can see the access to the correct ID I have with angularjs with your fiddle. One issue I have with this implementation though (and I am sure there is a solution) is if this select is part of a regular html form then the incorrect id gets submitted. – Martin Jul 29 '15 at 23:41
  • That's right. But why would you use 'regular form submitting' when working with angular? Are you aware of 'angular form submitting' using ng-model and ng-submit? That's the standard way to achieve this feature. see: http://jsfiddle.net/jergush/m1xkezk1/ – Jerguš Lejko Jul 30 '15 at 08:11