我能得到一个角元素编译的HTML? [英] Can I get the compiled html of an Angular element?
问题描述
我编使用$编译服务的元素。如果我直接添加到DOM,它看起来不错,所有绑定的是正确的。如果我想这个元素为一个字符串,虽然,它显示了 {{} stuffHere}
而不是绑定。有没有一种方法来获取元素的HTML它的编译后?
I have compiled an element using the $compile service. If I add that directly to the DOM, it looks great and all of the bindings are correct. If I want that element as a string though, it shows {{stuffHere}}
instead of the bindings. Is there a way to get the html of the element after it's compiled?
$templateCache.put('template', '<div><div><div><span>content is {{content}}</span></div></div> </div>');
$scope.content = 'Hello, World!';
var el = $compile($templateCache.get('template'))($scope);
$('body').append(el);
alert(el.html());
http://plnkr.co/edit/1sxvuyUZKbse862PieBa?p=$p$ PVIEW
追加到身体节目内容是为你好,元素世界!
警报显示&LT; DIV&GT;&LT; DIV&GT;&LT;跨度NG结合&GT; {{内容}}&LT; / SPAN&GT;&LT; / DIV&GT;&LT; / DIV&GT;
我想看看出来的警报是&LT; DIV&GT;&LT; DIV&GT;&LT;跨度NG结合&GT;的Hello World&LT; / SPAN&GT;&LT; / DIV&GT;&LT; / DIV&GT ;
What I would like to see out of the alert is <div><div><span ng-binding>Hello World</span></div></div>
推荐答案
的问题是你得太早读取元素的内容。如果添加了 $超时
你读它是正确的:
The issue is you're reading the contents of the element too early. If you add a $timeout
to your read it will be correct:
angular.module('demo', []);
angular.module('demo').controller('PopoverDemoCtrl', function($scope, $timeout, $compile, $templateCache) {
$templateCache.put('template', '<div><div><div><span>content is {{content}}</span></div></div></div>');
$scope.content = 'Hello, World!';
var el = $compile($templateCache.get('template'))($scope);
$('body').append(el);
$timeout(function() {
console.log(el.html());
}, 300); // wait for a short while
});
在 $编译
方法被调用后,它不会立即生效。这是由于在 $消化
周期,因为它使用了 $范围
它需要运行<$ C $看到C> $摘要周期如果说有什么影响 $ scope.content
。这就是为什么你必须设置一个 $超时
,你需要等待,直到前元素的 $消化
周期完成其实内容得到改变。你可以阅读更多的关于这一切联系在了一起如何这里
After the $compile
method is called it will not immediately take effect. This is due to the $digest
cycle, since it uses the $scope
it needs to run the $digest
cycle to see if anything has affected $scope.content
. This is why you have to set a $timeout
, you need to wait until the $digest
cycle completes before the element's content actually gets changed. You can read a bit more about how this all ties together here.
这篇关于我能得到一个角元素编译的HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!