有没有办法从 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
属性并将其分配给变量
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/