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

时间:2015-09-29 17:28:28

标签: javascript angularjs

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

如何通过编译步骤实现在幕后实例化的控制器,与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());
}

我-directive.js

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

1 个答案:

答案 0 :(得分:0)

试试这个:

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());
}