AngularJS Select with ngRepeat and ngOptions

By | June 1, 2017

AngularJS Select with ngRepeat and ngOptions

HTML select element with AngularJS data-binding.

The select directive is used together with ngModel to provide data-binding between the scope and the select tag control (including setting default values). Moreover it also handles dynamic option tag elements, which can be added using the ngRepeat or ngOptions directives. The ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create options in a dropdown list, another way to bind data in select is ng-options. The ng-options directive was made especially for filling a dropdown list with options, and has at least one important advantage: Dropdowns made with ng-options allows the selected value to be an object, rather than while dropdowns made from ng-repeat has to be a string.

output

Choosing between ngRepeat and ngOptions

In many cases, ngRepeat can be used on option tag elements instead of ngOptions to achieve a similar result. However, ngOptions provides some benefits:
more flexibility in how the select’s tag model is assigned via the select as part of the comprehension expression.
reduced memory consumption by not creating a new scope for each repeated instance. In addition, ngOptions
increased render speed by creating the options in a documentFragment instead of individually.

The ng-repeat directive has its limitations, the selected value must be a string.

For an example:

html:

script (controller):

AngularJS Select with ngRepeat and ngOptionsHow to create a simple tooltip in CSS3