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"}
];

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