假设我有以下两个指令:
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();
}
}
}
});
以下html:
<consumer-directive ng-click="consumerFunction()"/>
当指令加载转换按预期发生时,将控制器设置为我的apiDirective Controller。但是在consumerFunction中,控制器始终是null
。为什么?我怀疑它与第二次编译有关?
完全删除第二个编译会导致指令无效地呈现。为什么?
发生了什么,以及如何在不手动内联指令的属性级别控制器的情况下修复它?
答案 0 :(得分:0)
如果要查找某些内容(需要只返回控制器实例,而不是函数工厂),您需要有一个正在寻找控制器的指令实例。工作示例:http://plnkr.co/edit/XP3dV456M0No6nbx2zOW?p=preview
<body>
<div ng-app="test">
<consumer-directive api-directive ng-click="consumerFunction()">aaa</consumer-directive>
</div>