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
you can't refer the body element
.innerHTML
inside the controller scope !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()
"Don't design your page, and then change it with DOM manipulations" - Thinking in angularjs if I have a jquery background.
With angular, you put your event-binding in the view and don't do DOM manipulation in controllers. Here's the working Demo.
controller
HTML