这是重现我的问题的代码片段:
html:
...
<div ng-controller="worker as workerCtrl">
<my-directive label="label" controllerAs="workerCtrl" function="fileUpload(e, this.options)"></my-directive>
</div>
控制器:
...
function fileUpload(file, options){...}
...
指示:
function myDirective($compile) {
var directive = {
restrict: 'E',
link: link
};
return directive;
function link(scope, element, attrs) {
var htmlText = '<lx-file-input ' +
'change="'+attrs.controllerAs+'.'+attrs.uploadFunction+'" ' +
'label="'+attrs.label+'"></lx-file-input>';
element.replaceWith($compile(htmlText)(scope));
}
}
应该是:('lx-file-input' 是第 3 方指令...)
<lx-file-input change="workerCtrl.fileUpload(e, this.options)" label="someLabel"</lx-file-input>
问题是 Angular 编译和链接的时机已关闭,模板留下的是 HTML 字符串,而不是编译后的函数。我知道如果我将控制器设置在指令内,它会起作用,但我希望它在 HTML 的相同“workerCtrl”范围内使用相同的函数。