0

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

Aides
  • 3,643
  • 5
  • 23
  • 39
  • 2
    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. `document.body.innerHTML +=` is a bad idea in any scenario, but especially when using angular. – Rhumborl Apr 08 '16 at 10:19
  • @Rhumborl could you write that as an answer, since this is definitely the correct and well explained answer? – Aides Jun 16 '16 at 14:10

3 Answers3

2

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

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
1

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

ZEE
  • 5,669
  • 4
  • 35
  • 53
0

"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>
Community
  • 1
  • 1
Lukas Chen
  • 373
  • 7
  • 15
  • Thanks for the solution, the thing is that I wanted a technical explanation why this happens (I've been developing in Angular for multiple years and just stumbled across this when prototyping something) – Aides Apr 08 '16 at 11:14