Setting the Value Attribute in AngularJS' ng-options
One common challenge faced by AngularJS developers is setting the value property when utilizing the ng-options directive to populate a select tag. While documentation may seem ambiguous, the solution lies in the comprehension expression.
ngOptions Syntax
As indicated in the AngularJS documentation, ngOptions accepts a comprehension expression in one of the following formats:
Array Data Sources:
Object Data Sources:
Setting the Value for Array Data Sources
In your case, where you have an array of objects with "value" and "text" properties, the appropriate comprehension expression for setting the value attribute is:
<select ng-options="obj.value as obj.text for obj in array"></select>
Using the 'track by' Expression
In recent updates to AngularJS, a "track by" expression can be used to explicitly set the value of the select element's value attribute:
<select ng-options="obj.text for obj in array track by obj.value"></select>
Memory Aid
To simplify remembering this complex syntax, consider it an extension of Python's list comprehensions. As such, it follows the format:
label as value for item in collection track by trackexpr
For example, the following expressions are equivalents:
my_list = [x**2 for x in [1, 2, 3, 4, 5]] person.name for person in people
obj.value as obj.text for obj in array person as person.name for person in people
Additional Notes
The above is the detailed content of How to Set the Value Attribute in AngularJS' ng-options?. For more information, please follow other related articles on the PHP Chinese website!