从Angular JS中的控制器渲染已编译的模板

时间:2019-02-01 00:48:41

标签: javascript angularjs

我正在尝试将一些html呈现给具有AngularJS指令的DOM

HTML

<a ng-click="doThing()">hello 2015</a>

除了由于我的应用程序中的限制,我必须将其添加到控制器的视图中。我正在尝试使用$compile服务。

Controller.js

let html = '<a ng-click="doThing()">hello 2015</a>';

const compiledTemplate = $compile(html)($scope);

document.getElementById('wrapper').innerHTML = compiledTemplate[0].innerHTML;

$scope.doThing = function(){

    console.log('it worked!');
}

View.html

<div id="wrapper"></div> 

这将呈现正确的HTML,但指令不起作用。单击链接不会触发doThing()函数。

如何编译和渲染AngularJS模板的字符串表示形式,以使所有angular指令都起作用?

1 个答案:

答案 0 :(得分:1)

您的代码不起作用,因为您只是从编译指令中复制原始HTML字符串-没有复制任何绑定,仅复制了字符串。

最好使用HTML元素而不是HTML字符串来调用$compile(),如下所示:

//find the wrapper DOM element
const directiveTarget = document.getElementById('wrapper');

//put the raw HTML into it
directiveTarget.innerHTML = '<a ng-click="doThing()">hello 2015</a>';

//get the angularjs-friendly version of the element
const directiveElement = angular.element(directiveTarget);

//initialise AngularJS bindings
const compiledTemplate = $compile(directiveElement)($scope);