Injecting HTML into the DOM destroys the AngularJS events

主宰稳场 提交于 2019-12-25 12:08:40

问题


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

document.body.innerHTML += thirdPartyHTML;

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)?

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.


回答1:


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.

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

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

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



来源:https://stackoverflow.com/questions/23119434/injecting-html-into-the-dom-destroys-the-angularjs-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!