Let's say I have the following two directives:
angular.module('test').directive('apiDirective', function (){
return {
restrict: 'A',
controller: function () {
this.awesomeFunction = function () {
console.log("CHECK ME OUT BEING AWESOME");
}
}
}
});
angular.module('test').directive('consumerDirective', function ($compile) {
return {
restrict: 'E',
require: '?apiDirective',
transclude: true,
link: function (scope, element, attrs, controller, transcludeFn) {
console.log('preLink controller: ', controller);
transcludeFn(scope, function (tElem, tScope) {
if (attrs.apiDirective === undefined) {
element.attr('api-directive', '');
$compile(element)(scope);
}
element.html(tElem);
$compile(tElem)(tScope);
});
scope.consumerFunction = function () {
console.log('trying to consume the awesome', controller);
controller.awesomeFunction();
}
}
}
});
And the following html:
<consumer-directive ng-click="consumerFunction()"/>
When the directive loads transclusion occurs as expected, setting the controller to be my apiDirective Controller. However in the consumerFunction, the controller is always null
. Why? I suspect it has something to do with the second compile?
Removing the second compile entirely causes the directive to render nonfunctionally. Why?
What is going on, and how do I fix it without inlining the attribute level controller on the directive by hand?
plnkr demo: http://plnkr.co/edit/Lbh7T9FRg3nS6ERW4HtA