AngularJS Select

In AngularJS, you can create a dropdown list (select box) based on items in an array, or an object.


Using ng-options

You should use the ng-option directive to create a dropdown list, based on an object or an array in AngularJS.

See this example:

Test it Now

Note:

You can also use the ng-repeat directive to make the same dropdown list as ng-options.

See this example:

Test it Now

ng-options vs. ng-repeat

Although, both can be used for dropdown list, but 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, while 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, while dropdowns made from ng-repeat has to be a string.

Consider that you have an array of objects:

Limitation of ng-repeat

The ng-repeat directive has a limitation that the selected value must be a string:

See this example:

Test it Now

While using the ng-options directive, you can select an object value:

See this example:

Test it Now

Use data source as an object

We can also use data source as an object.

Consider that you have an object with following key-value pairs:

The expression in the ng-options attribute is a bit different for objects:

See this example:

Test it Now

Example2:

The selected value will always be the value in a key-value pair.

The value in a key-value pair can also be an object:

See this example:

Test it Now
Next TopicAngularJS DOM




Latest Courses