AngularJS 使用指令编译 html 并将输出作为字符串?

AngularJS compile html with directive and get output as string?

有没有办法从 AngularJS 控制器或服务到 "compile/interpolate/whatever" 带有指令的小型 html 模板,并获得最终的 HTML 输出作为字符串?

更详细一点,假设我的模板是这样的: var html = '<span my-directive="myVariable"></span>',而我的指令在操作 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>

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

干杯:)

您可以为此使用 $sce:

$scope.variable = $sce.trustAsHtml(yourHtmlString);

然后在您的 html 中您需要使用:

<div ng-bind-html="variable"></div>

$compile 将 HTML 字符串或 DOM 编译成模板并生成模板函数,然后可用于 link scope 和模板在一起。

如果您的要求是将已编译的指令附加到另一个指令中,您可以在 link 函数中完成。

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

您可以在 link 函数中使用上述代码所示的 $compile。

Plnkr Example 中提供的示例。

是的,你可以用指令编译 HTML(并为该指令提供parameters/variables),最终得到结果作为字符串

首先我们来看一下$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 并且这个范围必须作为参数提供给 link 函数 $compile(html)(scope)

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

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 中编译的指令未被任何变量参数化,但您当然可以更改它(请记住,编译指令模板中使用的所有变量都必须分配给您编译的范围)