I have a select tag (to be used for country selection) which I want to prefill with options using a directive:
<select class="countryselect" required ng-model="cust.country"></select>
My directive goes like
return {
restrict : "C",
link: function postLink(scope, iElement, iAttrs) {
var countries = [
["AND","AD - Andorra","AD"],
["UAE","AE - Vereinigte Arabische Emirate","AE"]
... //loop array and generate opt elements
iElement.context.appendChild(opt);
}
}
I am able to fill the select with additional options, but the ng-model binding does not work. Even if cust.country has a value (e.g. "UAE"), the option is not selected.
How to make the select display the value of cust.country? If think I have some timing problem here.
AngularJS ng-options DirectiveThe ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.
Use ng-init to set default value for ng-options . Save this answer.
ng-options is the directive which is designed specifically to populate the items of a dropdown list. One major advantage using ng-options for the dropdown is, it allows us to pass the selected value to be an object. Whereas, using ng-repeat the selected value can only be string.
You need to add the options to the ngModelController so that this works. E.g. like this:
return {
restrict : 'C',
require: ['select', 'ngModel'],
link: function(scope, element, attrs, controllers) {
var countries = [['A', 'text text']];
countries.forEach(option => {
const optionElement = angular.element('<option/>')
.attr('value', option[0])
.text(option[1]);
element.append(optionElement);
controllers[0].addOption(option.value, optionElement);
});
}
};
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