问题
I have this code in my directive
compile: function compile (tElement, tAttributes, transcludeFn) {
if (tAttributes.drag == 'false') {
tElement.find('.myclass').removeAttr('draggable');
}
//attrs.$set('ngModel', 'new value');
return {
pre: function preLink (scope, element, attributes, controller, transcludeFn) {
// Pre-link code goes here
},
post: function postLink (scope, element, attributes, controller, transcludeFn) {
This works fine
But i want to add attribute instead of remove attribute based on boolean like this
if (tAttributes.drag == 'true') {
tElement.find('.myclass').attr('draggable');
}
But this is not working.
I thing i need to recompile element after adding but i don't know how to do it
回答1:
Try adding the attribute in template function of the directive definition.
module.run(function ($templateCache, $http) {
$http.get('__templateURL__')
.then(function (response){
$templateCache.put('__templateID', response.data)
})
});
module.directive('x', function ($templateCache) {
return {
template: function (tEl, tAttrs) {
var template = $($templateCache.get('__templateID'));
if (tAttrs.drag == 'true') {
template.find('.myclass').attr('draggable');
}
return template[0].outerHTML;
}
}
});
回答2:
jQlite (angular's "jQuery" port) doesn't support lookup by classes.
find() - Limited to lookups by tag name
So you should try querySelector
if (tAttributes.drag == 'true') {
tElement[0].querySelector('.myclass').attr('draggable');
}
来源:https://stackoverflow.com/questions/28666974/not-able-to-add-attribute-in-directive-in-angular