简体   繁体   中英

How can I use vanilla JavaScript to insert HTML elements into an Angular application webpage?

I've created an external/public JavaScript library.

As I am testing it on an Angular 1.x web app by including the script in the <HEAD> , I've found that it breaks the Angular app by making clicks do nothing.

After hours of debugging namespace, properties, and functions; I've finally found the culprit is when I insert HTML elements into the webpage. My JS library is currently using this code to insert HTML into the webpage. How would I go about making it support Angular apps (or SPAs in general)?

var HTML_ELEMENTS = ['<h1>Hi</h1>', '<div>Hello again.</div>'];

for (var i = 0; i < HTML_ELEMENTS.length; i++) {
  document.body.innerHTML += HTML_ELEMENTS[i];
};

One of the reasons I add the HTML elements to the bottom of document.body is because I set these elements to have the highest z-index in the page, so any competing elements will yield the z-index to my inserted HTML elements.

Answering my own question with my implementation. All credit goes to @Cbroe for pointing me in the right direction.

Basically, you cannot use document.body.innerHTML with Angular, so here's what I ended up using instead:

var HTML_ELEMENTS = ['<h1>Hi</h1>', '<div>Hello again.</div>'];

for (var i = 0; i < HTML_ELEMENTS.length; i++) {
  var child = document.createElement('div');
  child.innerHTML = HTML_ELEMENTS[i];
  child = child.firstChild;
  document.body.appendChild(child);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM