AngularJS在innerHTML编辑中断了 [英] AngularJS breaks on innerHTML edit
问题描述
我创建了一个记录函数,它将文本追加到 document.body中.innerHTML
就像这样。
函数日志(文本)
{
document.body.innerHTML + = text +'< br>';
$ b 如果我现在从我的控制器范围调用这个函数,它会打破AngularJS。
有人可以解释这种行为吗?
演示 - 多次单击栏,它们会触发。点击foo一次,所有的点击事件都不起作用了。
解决方案因为您正在设置 innerHTML ,您正在有效地重新创建整个< body>
元素。控制器和指令链接到的元素被销毁,你的应用程序将中断(就像任何香草JavaScript事件处理程序一样)。
document.body .innerHTML + =
在任何情况下都是一个糟糕的主意,但在使用Angular时尤其如此。
如果您需要这样做,而且无法做到它通过标准的Angular绑定等,一个更好的选择将是 angular.element(body).append()
I just came across a really curious issue while fiddling around.
I have created a logging function which appends the text to document.body.innerHTML
like this.
function log(text)
{
document.body.innerHTML += text + '<br>';
}
If I now call this funciton from my controller scope it breaks AngularJS.
Could someone explain this behaviour?
Demo - click bar multiple times, they fire. click foo once, none of the click events work anymore
解决方案 Because you are setting the innerHTML
, you are effectively recreating the whole <body>
element. The elements the controllers and directives are linked to are destroyed and your application will break (as will any vanilla JavaScript event handlers).
document.body.innerHTML +=
is a bad idea in any scenario, but especially when using Angular.
If you need to do this, and cannot do it through standard Angular binding etc, a better option would be angular.element(body).append()
这篇关于AngularJS在innerHTML编辑中断了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!