I have read about it in other posts, but I couldn’t figure it out.
I have an array,
$scope.items = [
{ID: '000001', Title: 'Chicago'},
{ID: '000002', Title: 'New York'},
{ID: '000003', Title: 'Washington'},
];
I want to render it as:
<select>
<option value="000001">Chicago</option>
<option value="000002">New York</option>
<option value="000003">Washington</option>
</select>
And also I want to select the option with ID=000002.
I have read select and tried, but I can’t figure it out.
One thing to note is that ngModel is required for ngOptions to work… note the
ng-model="blah"which is saying “set $scope.blah to the selected value”.Try this:
Here’s more from AngularJS’s documentation (if you haven’t seen it):
For some clarification on option tag values in AngularJS:
When you use
ng-options, the values of option tags written out by ng-options will always be the index of the array item the option tag relates to. This is because AngularJS actually allows you to select entire objects with select controls, and not just primitive types. For example:The above will allow you to select an entire object into
$scope.selectedItemdirectly. The point is, with AngularJS, you don’t need to worry about what’s in your option tag. Let AngularJS handle that; you should only care about what’s in your model in your scope.Here is a plunker demonstrating the behavior above, and showing the HTML written out
Dealing with the default option:
There are a few things I’ve failed to mention above relating to the default option.
Selecting the first option and removing the empty option:
You can do this by adding a simple
ng-initthat sets the model (fromng-model) to the first element in the items your repeating inng-options:Note: This could get a little crazy if
foohappens to be initialized properly to something “falsy”. In that case, you’ll want to handle the initialization offooin your controller, most likely.Customizing the default option:
This is a little different; here all you need to do is add an option tag as a child of your select, with an empty value attribute, then customize its inner text:
Note: In this case the “empty” option will stay there even after you select a different option. This isn’t the case for the default behavior of selects under AngularJS.
A customized default option that hides after a selection is made:
If you wanted your customized default option to go away after you select a value, you can add an ng-hide attribute to your default option: