Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add options to a select with an AngularJS directive?

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.

like image 392
Federico Elles Avatar asked Aug 27 '13 07:08

Federico Elles


People also ask

How do you do ng-options?

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.

How do I set default selected value in ng-options?

Use ng-init to set default value for ng-options . Save this answer.

What is the difference between Ng-options and Ng-repeat?

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.


1 Answers

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);
        });
    }
};
like image 113
yankee Avatar answered Oct 10 '22 19:10

yankee