javascript - 在 Angular JS 中从 Controller 渲染已编译的模板

标签 javascript angularjs

我正在尝试将一些 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/

相关文章:

javascript - 关于一次性自重定义函数模式

javascript - SharePoint Online - Javascript 捆绑

html - Angular ,选择列表第一项为空

angularjs - 使用 ng-include 保留传统的 anchor 行为

javascript通过属性检查在另一个对象数组中添加或替换对象

javascript - ckeditor 将 html 内容显示为纯文本

javascript - 带括号的函数是什么意思?

javascript - AngularJS - 如何在指令中取消同步 $viewValue 和 $modelValue

javascript - AngularJS ngMessages 无法绑定(bind)到 $index 表达式

javascript - 在 ng-Repeat 中随机化数组