我正在尝试将一些 html 渲染到具有 AngularJS 指令的 DOM
HTML
<a ng-click="doThing()">hello 2015</a>
除了由于我的应用程序中的限制之外,我必须将其从 Controller 添加到 View 中。我正在尝试使用 $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 指令都起作用?
最佳答案
您的代码不起作用,因为您只是从编译的指令中复制原始 HTML 字符串 - 没有复制任何绑定(bind),只是复制字符串。
最好使用 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);
关于javascript - 在 Angular JS 中从 Controller 渲染已编译的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471388/