I currently have the following directive on my select
.
ng-options="option.value as option.title for option in exportTypes"
$scope.exportTypes = an array of objects each with title
, value
, and generatesFile
attributes. I'd like the generatesFile
attribute to be added as a data-generates-file
attribute on each <option>
that is generated for this select.
Any thoughts on how to do this?
Here is a directive which can be used to add custom attributes when using ng-options
with <select>
, so you can prevent using ng-repeat
.directive('optionsCustomAttr', function ($parse) {
return {
priority: 0,
require: 'ngModel',
link: function (scope, iElement, iAttrs) {
scope.addCustomAttr = function (attr, element, data, fnDisableIfTrue) {
$("option", element).each(function (i, e) {
var locals = {};
locals[attr] = data[i];
$(e).attr(iAttrs.customAttrName ? iAttrs.customAttrName : 'custom-attr', fnDisableIfTrue(scope, locals));
});
};
var expElements = iAttrs['optionsCustomAttr'].match(/(.+)\s+for\s+(.+)\s+in\s+(.+)/);
var attrToWatch = expElements[3];
var fnDisableIfTrue = $parse(expElements[1]);
scope.$watch(attrToWatch, function (newValue) {
if (newValue)
scope.addCustomAttr(expElements[2], iElement, newValue, fnDisableIfTrue);
});
}
};
})
And then in your select,
<select ng-model="selectedExportType" ng-options="option.value as option.title for option in exportTypes"
options-custom-attr="option.generatesFile for option in exportTypes"
custom-attr-name="data-generates-file">
</select>
Note: This is a modified version of optionsDisabled
directory mentioned here