在angularjs中将编译的dom转换为html代码 [英] Convert compiled dom to html code in angularjs
问题描述
我写了一个指令,它有一个 postLink
,我编译了一些 html 代码并通过 angularjs 呈现它.但问题是我无法从生成的 DOM 中获取 html 代码.
I wrote a directive which has a postLink
, and I compiled some html code and render it by angularjs. But the problem is I can't get the html code from the generated DOM.
我的代码是:
app.directive("showResultAsText", ['$compile', function ($compile) {
return {
restrict: 'A',
compile: function compile(tElement, tAttrs, transclude) {
console.log('compile');
var watchModal = tAttrs["showResultAsText"];
var elem = jQuery(tElement);
var oriHtml = elem.html();
elem.empty();
return {
post: function postLink(scope, iElement, iAttrs, controller) {
scope.$watch(function () {
return scope.$eval(watchModal);
}, function (newVal) {
if (newVal) {
var s = $compile(angular.element(oriHtml))(scope);
console.log(s);
console.log(s[0]);
console.log(s[0].outerHTML);
console.log($('<div>').append(s[0]).html());
iElement.text(s[0].outerHTML);
}
});
}
}
}
}
}
你可以看到我使用了 console.log
来打印 s
的值.在控制台中,它输出:
You can see I used console.log
to print the value of s
. And in the console, it outputs:
你可以看到console.log(s)
和console.log(s[0])
有很多信息,但是当我使用outerHTML
代码>,里面的按钮都不见了.
You can see console.log(s)
and console.log(s[0])
have many information, but when I use outerHTML
, the inner buttons are all missing.
我也尝试使用 jquery:jQuery(s[0]).html()
,但同样发生了.
I also tried to use jquery: jQuery(s[0]).html()
, but the same happened.
将 s
转换为 html 代码的正确方法是什么?
What is the correct way of convert that s
to html code?
推荐答案
如果你能提供一个 plunkr/jsFiddle-example 会更容易,但我想我知道出了什么问题.您被控制台愚弄了 - 当您执行 console.log(s) 时,它不会立即被记录(它是异步的)- 控制台会获得对 dom 元素 s[0] 的引用,并且到了它的时候准备打印 angular 已经完成了它的渲染.另一方面, s[0].outerHTML 和 s.html() 是同步的,所以你会得到预先角度渲染的结果.要解决此问题,您只需执行一个简单的 setTimeout:
It'd be easier if you could provide a plunkr / jsFiddle-example, but I think I know what's wrong. You're getting fooled by the console - when you you do console.log(s) it doesn't get logged immediately (it's async) - the console gets a reference to the dom element s[0], and by the time it's ready to print angular is done with it's rendering. On the other hand, s[0].outerHTML and s.html() are synchronous, so you get the pre-angular rendered result. To fix this you could just do a simple setTimeout:
setTimeout(function(){ console.log(s[0].outerHTML); });
Angular 现在应该有时间在回调之前进行渲染(我认为您不需要延迟,但我可能错了).您还可以使用 angular $timeout-service,它用 $scope.$apply 包装回调函数 - 请参阅 http://docs.angularjs.org/api/ng.$timeout
Angular should now have time to do it's rendering before the callback (I don't think you need a delay, but I might be wrong). You can also use the angular $timeout-service which wraps the callback-function with $scope.$apply - see http://docs.angularjs.org/api/ng.$timeout
这篇关于在angularjs中将编译的dom转换为html代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!