Injecting HTML into the DOM destroys the AngularJS

2019-09-01 01:25发布

问题:

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