Federico Elles Federico Elles - 1 year ago 43
AngularJS Question

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

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.

Answer Source

You can use directive from Angular JS:


<div ng-controller="MainCtrl">
<select ng-model="country" ng-options="c.name for c in countries"></select>


app.controller('MainCtrl', function($scope) { 
   $scope.countries = [
    {name:'Vereinigte Arabische Emirate', value:'AE'},
    {name:'Andorra', value:'AD'},

  $scope.country = $scope.countries[1]; 


Check the docs of select: Angular Select



  app.directive('sel', function () {
    return {
        template: '<select ng-model="selectedValue" ng-options="c.name for c in countries"></select>',
        restrict: 'E',
        scope: {
            selectedValue: '='
        link: function (scope, elem, attrs) {
            scope.countries = [{
                name: 'Vereinigte Arabische Emirate',
                value: 'AE'
            }, {
                name: 'Andorra',
                value: 'AD'
            }, ];
            scope.selectedValue = scope.countries[1];

Main controller:

app.controller('MainCtrl', function($scope) {




<div ng-controller="MainCtrl">
<sel selected-value="country"></sel>

Working Example: EXAMPLE