AngularJS breaks on innerHTML edit

2019-09-15 19:09发布

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

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-15 19:27

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

查看更多
冷血范
3楼-- · 2019-09-15 19:31

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

查看更多
何必那么认真
4楼-- · 2019-09-15 19:53

"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>
查看更多
登录 后发表回答