Over the past week I kept running into the issue of iterating over an array or an object in a <select>
field with ng-repeat
, only to find that I had a blank option as the first item in the dropdown. After trying several strategies, I finally found one that worked.
Let’s say you want to iterate over the array ctrl.items
in your <select>
field.
some.component.js
(function() { 'use strict'; function SomeController() { var ctrl = this; // item array for dropdown ctrl.items = [ { select: 'data1', label: 'Option 1' }, { select: 'data2', label: 'Option 2' }, { select: 'data3', label: 'Option 3' } ]; } angular .module('app') .component('someComponent', { controller: SomeController, templateUrl: '/app/components/some.component.html', }); })();
ng-repeat
, this can be accomplished with ng-options
.
ng-options
Pattern Usage:
select
as
label
for
value
in
array
some.component.html
<select name="selectName" ng-model="$ctrl.formName.selectName" ng-options="item.select as item.label for item in $ctrl.items"> <!-- this option sets the dropdown placeholder --> <!-- value must be an empty string for this to work --> <option value="" selected="selected">Select an Item</option> </select>
select
: value that will be submitted or bound to the model of the parent
label
: each <option>
shown in dropdown list
value
: local variable for each array
item or object
property value being iterated over.
You can find more ng-options
usage patterns in the AngularJS API Documentation