Aides Aides - 5 months ago 37
AngularJS Question

AngularJS breaks on innerHTML edit

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

Answer

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

Comments