0

从模板编译后,是否可以动态关联控制器?

//Controller /path/ctrl/MainCtrl.js
angular.module('app')
    .controller('MainCtrl', function () {

    });

//Directive  /path/dir/myDir.js
function link(scope, element, attrs) {
    $templateRequest('path/oneTpl.tpl').then(function (html) {
        $compile(element.html(html).contents())(scope);
        //How can I do to dynamically inject MainCtrl into the oneTpl.tpl template using the path (/path/ctrl/MainCtrl.js)?
    });
}
4

1 回答 1

1

您可以尝试向已编译的模板添加一个属性(很高兴知道您的模板到底是什么)。

试试下面的代码:

element.setAttribute(name, value);

例子:

<button>Hello World</button>
var b = document.querySelector("button"); 

b.setAttribute("disabled", "disabled");

因此,您只需要模板的标识符,例如 id 或类,然后设置您的属性。

查询:$('#yourTemplate').setAttribute('ng-controller','yourController' );

如果这对您没有帮助,也许以下线程会对您有所帮助:

AngularJS:从 ng-repeat 动态分配控制器

动态 NG-控制器名称

在运行时动态分配 ng-controller

于 2016-02-16T12:11:22.913 回答