I developed an Angular directive like this:
'use strict';
angular.module('countrySelect', [])
.directive('countrySelect', ['$parse', function($parse) {
var countries = [
{ code: "af", name: "Afghanistan" },
{ code: "ax", name: "Åland Islands" },
{ code: "al", name: "Albania" },
{ code: "dz", name: "Algeria" },
];
return {
template: '<select ng-options="c.code as c.name for c in countries">',
replace: true,
link: function(scope, elem, attrs) {
scope.countries = countries;
if (!!attrs.ngModel) {
var assignCountry = $parse(attrs.ngModel);
elem.bind('change', function(e) {
assignCountry(elem.val());
});
scope.$watch(attrs.ngModel, function(country) {
elem.val(country);
});
}
}
}
}]);
In the HTML template, I have a select field set up like this:
<div country-select ng-model="citizenship"></div>
After selecting an option, the model updates with the country code as expected. However, the country name does not appear in the select field until I reselect it.
The current process is as follows:
- Click
- Select country
- Model updates with country code, but name doesn't display in the select field
- Click and reselect
- Name appears in the select field
How can I make the select field show the country name upon selection?