Aides
Aides

Reputation: 3683

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

Upvotes: 0

Views: 689

Answers (3)

Rhumborl
Rhumborl

Reputation: 16609

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

Upvotes: 2

Lukas Chen
Lukas Chen

Reputation: 383

"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

self.fooLog = [];

self.foo = function()
{
    self.fooLog.push("foo");
};

HTML

<div ng-repeat="foo in test.fooLog track by $index">
  {{foo}}
</div>

Upvotes: 0

ZEE
ZEE

Reputation: 5869

you can't refer the body element .innerHTML inside the controller scope !

Upvotes: 1

Related Questions