Home >Web Front-end >JS Tutorial >How do I set the value attribute in ng-options for AngularJS?
AngularJS's ng-options directive allows developers to populate options for a
To understand the value setting mechanism, let's delve into the syntax of ngOptions. It takes an expression in one of these forms:
For arrays:
label for value in array
For objects:
label for (key, value) in object
Consider the following example array:
array = [{ "value": 1, "text": "1st" }, { "value": 2, "text": "2nd" }];
To fill the options using ng-options, we can write:
<select ng-options="obj.text as obj.value for obj in array"></select>
In this case, obj.value will determine the selected value for each option.
Update: Track by Value Expression
With recent AngularJS updates, it's now possible to explicitly specify the value for the value attribute using a track by expression:
<select ng-options="obj.text for obj in array track by obj.value"></select>
Remembering the Syntax
The ngOptions syntax can be challenging to recall. A helpful analogy is to think of it as an extended version of Python's list comprehensions:
[x**2 for x in [1, 2, 3, 4, 5]]
However, in ng-options, we distinguish between the value and the text displayed for each option using the as keyword:
person.id as person.name for person in people
For JavaScript objects, the syntax is similar, using (key, value) pairs:
for (key, value) in object
The above is the detailed content of How do I set the value attribute in ng-options for AngularJS?. For more information, please follow other related articles on the PHP Chinese website!