使用“controller as ...”语法

时间:2015-07-14 08:56:13

标签: 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>

控制器:

...
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'是第三方指令......)

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

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

2 个答案:

答案 0 :(得分:1)

首先,您可以尝试从外部传递函数,例如官方Angular guide中的on-close

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

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

最近我和刚刚发布的answer几乎相同。你也可以在那里找到其他有用的帖子。

答案 1 :(得分:1)

相关问题