简体   繁体   中英

Angular inside of Angular - solving: WARNING: Tried to load angular more than once

I have a small angular app that just has one directive.

It will be used on many other websites, simply by them including one JS file and then using the directive anywhere on their page.

The problem is that if I try to do this on a site that happens to also use angular, I get the classic

WARNING: Tried to load angular more than once.

This is because angular loads itself on the global namespace.

I have tried messing with the angular.js code, doing find-and-replace on instances of things like:

angular = window.angular || (window.angular = {})

to

angular = window.angularXYZ || (window.angular = {})

But it didn't work and it seems very hacky.

Any ideas for namespacing an entire angular app so that it can play nicely when initialized from within other angular apps?

A crazy but also the most realistic solution would be to load your code in an iframe.

I think the variable you're using may be incorrect, at least according to this blog post :

if (window.angular.bootstrap) {
  // already loaded
} else {
  // magic: somehow namespace the angular app!
}

I know it might be a pain, but if angular is already loading on one site, I would suggest you log the version of angularjs it's using and test your code against it. Otherwise you're loading up a relatively heavy framework twice .

Obviously if there's lots of versions of angularjs being used, you should only test against the most common version and the version you're currently using and suggest to the client to upgrade their version of angularjs.

what you can do is.

if (typeof angular === 'undefined') {  
  document.write('<script type="text/javascript" src=""angular.min.js""></script>');
}

this way angular would be loaded only if its not defined already...

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