简体   繁体   中英

How to dynamically inject modules and services into app and controllers in AngularJS?

I have an app that decides if it needs a specific set of modules inside of the application run block. (Removed all unnecessary logic)

angular.module('myApp', []).run(function () {
    if (true) {
        //needs to have modules injected into myApp
    }
});

How can I add modules to myApp, after my angular app has initiated?

Once the module is injected dynamically, how can I use the injected module's services in other places of my app, like controllers and directives?

angular.module('myApp').controller(function ($scope, myService) {  //where myService belongs to a dynamically added module

    myService.doStuff(); //this would give me an error if the module wasn't injected
});

I know it's possible to just add all modules with Inline Array Annotation, then just checking if myService exists, inside of my controllers. But I'm trying to do this the correct way, instead of having to check for myService, thought-out my whole code base.

I appreciate any help!

You can explicitly bootstrap your application module after determining what you need.

var modulesToInject = ["myDep1"];
// push more modules here as needed
angular.module("myApp", modulesToInject);
angular.bootstrap(document,["myApp"]);

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