AngularJS 使用指令编译 html 并以字符串形式输出?

标签 angularjs templates compilation interpolation

有没有办法从 AngularJS Controller 或服务“编译/插值/其他”带有指令的小型 html 模板,并以字符串形式获取最终的 HTML 输出?

更详细地说,假设我的模板是这样的: var html = '<span my-directive="myVariable"></span>' ,并且 my-directive 在操作 myVariable 时添加额外的 html。

现在,我想编译该 html $compile(html)({myVariable: myVariable}) (不确定这是否是正确的方法)最后有一个完整的 html 作为字符串作为最终结果:

<span my-directive="myVariable">
 <span>additional content added by my amazing directive while manipulating myVariable</span>
</span>

知道如何实现这一目标吗?非常感谢任何建议。

干杯:)

最佳答案

是的,您可以使用指令编译 HTML(并且还为该指令提供参数/变量)并最终获得字符串形式的结果

首先我们来看一下$compile documentation (Usage section)

我们可以看到 $compile 参数是

Element or HTML string to compile into a template function.

在你的情况下它是var html

返回值为

a link function which is used to bind template (a DOM element/tree) to a scope

$compile 返回一个需要范围作为参数的函数

scope 是一个特殊对象,因此您的 {myVariable: myVariable} 无效,如果您想将变量传递给编译,则必须将此变量分配给当前作用域 scope。 myVariable = myVariable 并且此范围必须作为链接函数 $compile(html)(scope)

的参数提供

现在我们必须检查链接函数返回的内容:

Calling the linking function returns the element of the template

瞧! - 我们有Element Object,因此我们可以获取其outerHTML属性并将其分配给变量

Pradeep Plunker你可以改变

var str = '<div my-directive>Hello world</div>'
var com = $compile(str)(scope);
element.append(com);

var str = '<div my-directive>Hello world</div>'
var com = $compile(str)(scope);
console.log('outerHTML',com[0].outerHTML);
element.append(com[0].outerHTML);

在控制台中观看结果:)

注意:在 Plunker 中编译的指令不由任何变量参数化,但您当然可以更改它(只需记住编译指令模板中使用的所有变量都必须分配给您编译的范围)

关于AngularJS 使用指令编译 html 并以字符串形式输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47845311/

相关文章:

c++ - "Class"从模板类派生时没有命名类型

c++ - clang 如何引导 C/C++ 代码优化?

scala - 编译后 SBT 应用任务

c++ - 子类中的类模板非类型成员访问

php - PHP/HTML替换/模板引擎

compiler-errors - 在环境变量CC(MPI,Intel编译器,包装器)中找不到编译器集

javascript - AngularJS:打开新窗口并维护双向数据绑定(bind)

angularjs - 找不到模块 'true-case-path'

javascript - Angular JS Controller 未实例化

javascript - 对具有特定属性的数组元素求和