5

这是重现我的问题的代码片段:

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”范围内使用相同的函数。

4

2 回答 2

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>

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

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

于 2015-07-17T23:12:05.393 回答
1

我在这里发布了我的解决方案:https ://github.com/formly-js/angular-formly-templates-lumx/issues/12#issuecomment-126464833

于 2015-07-30T21:47:41.550 回答