I have an angular directive like so:
'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);
});
}
}
}
}]);
And a select field in the template like so:
<div country-select ng-model="citizenship"></div>
I can select an option, and the model gets updated with the country code as intended, but the country name does not appear in the select field unless I choose it again.
In other words, the process goes
How do I get the select field to display the country name upon select?
Since you are using replace: true original ng-model="citizenship" is going to end up on select element anyway, so you don't need to handle select change events in order to update ngModel, it's already bound to select box. So your directive should look just like this:
angular.module('countrySelect', [])
.directive('countrySelect', [function() {
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"></select>',
replace: true,
link: function(scope, elem, attrs) {
scope.countries = countries;
}
}
}]);
Demo: http://plnkr.co/edit/9aBhrlIqPIGkGTNTwIb6?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With