从手动$compile调用中获取控制器

Get the controller from a manual $compile invocation

本文关键字:获取 控制器 调用 compile      更新时间:2023-09-26

我正在使用以下命令手动渲染指令。

我怎么能得到控制器实例化背后的编译步骤,与my-directive指令相关联的场景?

function renderDirective(hostElement) {
    var $injector, $compile, link;
    $injector = hostElement.injector();
    $compile = $injector.get('$compile');
    link = $compile(angular.element('<my-directive></my-directive>'));
    // ... how can I get the controller instance 
    // associated with the instance of my-directive 
    // that has been instantiated by the previous 
    // line of code?
    return link(createScope());
}

my-directive.js

return function MyDirective() {
    return {
        scope: {
            'context': '='
        },
        restrict: 'E',
        template: template,
        controller: 'myController',
        controllerAs: 'ctrl',
        replace: true,
    };
};

试试这个:

function renderDirective(hostElement) {
    var $injector, $compile, link;
    $injector = hostElement.injector();
    $compile = $injector.get('$compile');
    link = $compile('<my-directive></my-directive>');
    // ... how can I get the controller instance 
    // associated with the instance of my-directive 
    // that has been instantiated by the previous 
    // line of code?
    return link(createScope());
}