我正在尝试在我的 Controller 上编译一些 HTML,如下所示:
$scope.online = networkService.isOnline();
var wrapper = angular.element(document.createElement("i"));
var compiledContents = $compile($scope.chapter.contents);
var linkedContents = compiledContents($scope);
wrapper.append(linkedContents);
$scope.chapter.linkedContents = wrapper.html();
正在编译的 HTML 有一些带有 ng-if='online'
的元素。但编译后的 HTML 总是会带有注释的元素,就好像 online
不是真的(事实确实如此 - 我什至添加了 console.log(scope.online )
在 Angular 的 $compile 函数中,它打印 true)。
我在这里遗漏了什么吗?
最佳答案
wrapper.html()
返回一个表示元素内部 HTML 的字符串。然后,您将该字符串分配给 $scope.chapter.linkedContents
。尽管从您的问题中不清楚您实际如何以及在何处使用 $scope.chapter.linkedContents
,但有一件事是肯定的 - 该字符串绝对没有以任何方式“链接”。
实际的“linkedContents”是最终应该出现在 DOM 中的元素。在你的例子中,它是 wrapper
元素及其内容,但同样不清楚,它如何(如果有的话)最终出现在 DOM 中。
但是您甚至不应该在 Controller 中处理 DOM。 Controller 与 DOM 无关,因此您应该看到一个很大的警告信号,表明您做错了什么。确保您了解 Controller 、指令等的 Angular 色...
我想我明白你想要解决的问题是什么。您会得到一些动态的未编译的 HTML(或实际元素) - 即 $scope.chapter.contents
,您需要将其放置在 DOM 中并进行编译/链接。
通常,要绑定(bind) HTML,可以使用 ng-bind-html
(假设它是受信任的或已启用清理功能):
<div ng-bind-html="chapter.contents">
</div>
但这不会被 $compiled。要进行编译,我建议编写您自己的指令,该指令的工作方式与 ng-bind-html 类似,但也可以对其进行编译:
<div compile-html="chapter.contents">
</div>
然后,指令将获取内容,针对某个范围(例如子范围)编译/链接它,并将其附加到托管指令 compileHtml
的元素。
.directive("compileHTML", function($compile, $parse){
return {
scope: true,
link: function(scope, element, attrs){
// get the HTML content
var html = $parse(attrs.compileHtml)(scope);
element.empty();
// DISCLAIMER: I'm not dealing with sanitization here,
// but you should keep it in mind
$compile(html)(scope, function cloneAttachFn(prelinkContent){
element.append(prelinkContent);
});
}
};
})
关于javascript - $compile 链接函数显然不适用范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586918/