使用"controller as ..."语法时,在另一个指令中的第三方指令

Sag*_*ina 5 javascript angularjs angularjs-directive lumx

这是重新创建我的问题的代码片段:

HTML:

...
<div ng-controller="worker as workerCtrl">
    <my-directive label="label" controllerAs="workerCtrl" function="fileUpload(e, this.options)"></my-directive> 
</div>
Run Code Online (Sandbox Code Playgroud)

控制器:

...
function fileUpload(file, options){...}
...
Run Code Online (Sandbox Code Playgroud)

指示:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

应该是:('lx-file-input'是第三方指令......)

<lx-file-input change="workerCtrl.fileUpload(e, this.options)" label="someLabel"</lx-file-input>
Run Code Online (Sandbox Code Playgroud)

问题是Angular编译和链接的时间关闭,模板留下HTML字符串而不是编译的函数.我知道如果我将控制器设置在指令中但它希望它在HTML中的相同"workerCtrl"范围内使用相同的函数,它将起作用.

Gáb*_*mre 1

on-close首先你可以尝试像官方Angular 指南中那样从外部传递函数。

<div ng-controller="Controller">
  {{message}}
  <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog(message)">
    Check out the contents, {{name}}!
  </my-dialog>
</div>
Run Code Online (Sandbox Code Playgroud)

但我不明白为什么你不应该在调用所需函数的指令范围内创建一个桥接函数。我更喜欢这种方式。

最近我的答案与您刚刚发布的几乎相同。您也可能在那里找到其他有用的帖子。