Create a drop-down list with custom options text and value in Angular

It is a common practice that the text of the options of a select drop-down box is a combination of a shortcut and it’s full text label.

For example consider the following array of JSON objects that a server might return:

1
2
3
4
var countries = [
    {"shortcut": "DE", "label": "Germany"},
    {"shortcut": "GB", "label": "Great Britain"}
];
  • On the UI-side we want the options on the drop-down box to have the following format: label (shortcut).
  • We also want that the value property of each option contains the country shortcut, so that it’s easier for the server to parse the selected options later.
  • Moreover, since the server might return hundreds of options, we want a way to dynamically generate the option elements.

Angular has a solution to all three previous requests. Consider the following code:

1
2
3
<select ng-model="countries" name="countries"
ng-options="country as combineProperties(country) for country in countries track by country.shortcut">
</select>

The track by defines which property is going to be used as value on the option element and the combineCountryShortcutWithLabel(country) is the function inside the Angular controller which combines the strings of the two properties:

1
2
3
$scope.combineProperties = function (country) {
    return country.label + " (" + country.shortcut + ")";
}

More information on the ngOptions directive can be found in the official Angular documentation.

comments powered by Disqus