将 HTML 注入 DOM 会破坏 AngularJS 事件 [英] Injecting HTML into the DOM destroys the AngularJS events

查看:20
本文介绍了将 HTML 注入 DOM 会破坏 AngularJS 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 angularJS 应用程序中包含了一个第三方脚本,它在正文中附加了一些 HTML

I have included a third party script in my angularJS app, which appends some HTML to the body

document.body.innerHTML += thirdPartyHTML;

无论何时完成,我的 ng-click 事件似乎都不会触发.第三方脚本的 HTML 是否以错误的方式附加了 HTML,或者我应该以某种方式刷新 DOM ($scope.$apply) 上的 AngularJS 视图?

Whenever that is done it seems like my ng-click events won't fire. Is the HTML by the third party script appending the HTML in the wrong way, or should I somehow refresh AngularJS view on the DOM ($scope.$apply)?

更新:似乎我可以重现错误,只需调用 document.body.innerHTML += '';我.它显然与 onclick 事件无关.如果你有自己的 AngularJS 应用,你可以尝试调用 document.body.innerHTML += '';文档加载后,所有 ng-click 事件都不起作用.

Update: It seems like I can reproduce the error, with just calling document.body.innerHTML += ''; myself. It apparently hasn't anything to do with the onclick event. If you have your own AngularJS app, you can try to call document.body.innerHTML += ''; after the document has loaded, and none of the ng-click events work.

推荐答案

每当 innerHTML 更改时,浏览器都必须重新创建 DOM 树.这意味着与现有 DOM 元素关联的所有信息都将丢失.

Whenever innerHTML is changed the browser has to recreate the DOM tree. That means that all information associated with the existing DOM elements is lost.

这不仅包括事件监听器.Angular 在 DOM 元素上存储作用域和控制器.所以基本上这个应用程序没有了.

This does not only include event listeners. Angular stores scopes and controllers on DOM elements. So basically the application is gone.

如果第三方应用真的改变了body元素的innerHTML,那么你最好让它在angular之前运行.

If the third party app really changes the innerHTMLof the body element, then you better let it run before angular.

作为替代方案,您可以手动初始化应用程序,而不使用 ng-app.详细信息可以在这里

As an alternative you can initialize the application manually and don't use the ng-app. The details can be found in here

这篇关于将 HTML 注入 DOM 会破坏 AngularJS 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆