I have a custom Angular directive called <my-button>
where I want to run another directive (my-fun-directive
) on its output. To achieve this, I am using $compile
instead of a directive template. However, it seems that using this method does not allow me to pass additional HTML attributes or ng-*
attributes.
Custom Directive
app.directive('myButton', function ($compile) {
return {
restrict: 'E',
replace: true,
scope: true,
link: function (scope, element, attrs) {
var btnTxt = attrs.text || "";
scope.buttonInnerHtml = attrs.icon ? '<span class="glyphicon glyphicon-' + attrs.icon + '"></span> ' + btnTxt : btnTxt;
var template = '<button type="button" class="myCustomClass" ng-bind-html="buttonInnerHtml" my-fun-directive></button>';
var content = $compile(template)(scope);
element.replaceWith(content);
}
};
});
Usage Example
<my-button
icon="ok"
text="Save Changes"
class="anotherClass"
ng-hide="someProperty"
ng-click="myClickEvent()"
example-directive></my-button>
Current Output (line breaks added for readability)
<button
type="button"
class="myCustomClass"
ng-bind-html="buttonInnerHtml"
my-fun-directive>
<span class="glyphicon glyphicon-ok"><span> Save Changes
</button>
Desired Output (line breaks added for readability)
<button
type="button"
class="myCustomClass anotherClass"
ng-bind-html="buttonInnerHtml"
ng-hide="someProperty"
ng-click="myClickEvent()"
my-fun-directive
example-directive>
<span class="glyphicon glyphicon-ok"><span> Save Changes
</button>
In the desired output, notice the inclusion of ng-*
attributes, an additional directive, and an added CSS class. How can I ensure that all these elements work together seamlessly?