Refer to the documentation for more information on ngOptions
ngOptions(optional) – {comprehension_expression=
} – can be used in various forms depending on the data source:
For array data sources:
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array track by trackexpr
For object data sources:
label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object
In your scenario, it should look like this:
array = [{ "value": 1, "text": "1st" }, { "value": 2, "text": "2nd" }];
<select ng-options="obj.value as obj.text for obj in array"></select>
Update
With recent updates in AngularJS, you can now set the actual value for the value
attribute of the select
element using the track by
expression.
<select ng-options="obj.text for obj in array track by obj.value">
</select>
How to remember this syntax
Struggling to remember this syntax? Think of it like an extended version of Python's list comprehensions. For example:
Python code:
my_list = [x**2 for x in [1, 2, 3, 4, 5]]
> [1, 4, 9, 16, 25]
# Let people to be a list of person instances
my_list2 = [person.name for person in people]
> my_list2 = ['Alice', 'Bob']
This concept is similar to the ngOptions syntax explained earlier. It helps to differentiate between the actual values in the code and the displayed labels in a <select>
element.
For JavaScript objects, use the same method with deconstructed (key, value)
pairs to handle items in the object.