re-open and add dependencies to an already bootstrapped application

南笙酒味 提交于 2019-11-27 17:33:52

I solved it like this:

reference the app again:

var app = angular.module('app');

then push your new requirements to the requirements array:

app.requires.push('newDependency');

Simple... Get an instance of the module using the getter like this: var app = angular.module("App");

Then add to the "requires" collection like this: app.requires[app.requires.length] = "ngResource";

Anyway, this worked for me. GOOD LUCK!

Matt Nibecker

According to this proposal on the Angular JS google group this functionality does not exist as of this moment. Hopefully the core team decides to add this functionality, could use it myself.

Amir

If you wish to add multiple dependencies at once, you can pass them in push as follows:

<script>
    var app = angular.module('appName');
    app.requires.push('dependencyCtrl1', 'dependencyService1');
</script>
tjespe

I realize that this is an old question, however, no working answer has yet been provided, so I decided to share how I solved it.

The solution requires forking Angular, so you can't use CDN anymore. However the modification is very small, so I am surprised why this feature doesn't exist in Angular.

I followed the link to google groups that was provided in one of the other answers to this question. There I found the following code, which solved the issue:

instanceInjector.loadNewModules = function (mods) {
  forEach(loadModules(mods), function(fn) { instanceInjector.invoke(fn || noop); });
};

When I added this code to line 4414 in the angular 1.5.0 source code (inside the createInjector function, before the return instanceInjector; statement), it enabled me to add dependencies after bootstrapping like this $injector.loadNewModules(['ngCookies']);.

Since version 1.6.7 it is now possible to lazy load modules after the app has been bootstrapped using $injector.loadNewModules([modules]). Below is an example taken from AngularJS documentation:

app.factory('loadModule', function($injector) {
   return function loadModule(moduleName, bundleUrl) {
     return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); });
   };
})

Please read full documentation about loadNewModules as there are some gotchas around it.

There's also a very good sample app by omkadiri using it with ui-router.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!