Call another directive from the directive with the same attributes and content
-
21-12-2019 - |
Question
I want to override behaviour of one library directive, called "ui-sref". Lets see example:
<a ui-sref="edit" class="btn btn-small">
<i class="icon-pencil"></i> Edit
</a>
Now, I want to create my own directive called, for example, "ui-sref-appended". Code will be like this:
<a ui-sref-appended="edit" class="btn btn-small">
<i class="icon-pencil"></i> Edit
</a>
The output I want must be:
<a ui-sref="user.edit" class="btn btn-small">
<i class="icon-pencil"></i> Edit
</a>
(and then complied, so ui-sref could done his job)
How can I implement this? The problem is that i want my a to have the same attributes and content, but changed from ui-sref-appended="edit" to ui-sref="user.edit"
Solution
Set template of your new directive as follows
template : '<a ui-sref="user.edit" class="btn btn-small"> <i class="icon-pencil"</i> Edit</a>';
And set the user.edit in the link function or pass the user to directive via scope member.
If you have dynamic template, you can create the directive template in link function.
app.directive('newDirective', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var template= '<a ui-sref="user.edit" class="{{btnClass}}"> <i class="icon-pencil"</i> Edit </a>';
element.append($compile(template)(scope));
},
scope: {
user: '=',
btnClass: '@'
}
}
});
EDIT
If you want to just set the ui-sref, simply add the ui-sref as an attribute to your element and then compile it.
app.directive('uiSrefAppended', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.attr('ui-sref', 'user.edit');
$compile(element)(scope);
},
scope: {
user: '='
}
}
});