How add options to a select with an AngularJS directive?
33,476
Solution 1
You can use directive from Angular JS:
Markup:
<div ng-controller="MainCtrl">
<select ng-model="country" ng-options="c.name for c in countries"></select>
{{country}}
</div>
Script:
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
EDIT WITH DIRECTIVE
Directive:
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) {
$scope.country={};
})
Markup:
<div ng-controller="MainCtrl">
<sel selected-value="country"></sel>
{{country}}
</div>
Working Example: EXAMPLE
Solution 2
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);
});
}
};
Author by
Federico Elles
Updated on March 29, 2020Comments
-
Federico Elles over 4 years
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.
-
Federico Elles almost 11 yearsI agree that for a single country-select field this is the perfect solution. In my case I have several county-select fields, so I want to make it more reuseable.
-
Norbert Pisz almost 11 yearsPlease check my edit. Now you have all in directive and can easy bind to other varibles.
-
developer10 about 10 yearsI would also suggest using
replace: true
here as it would remove the wrapping<sel>
element from the final HTML markup.