简体   繁体   English

如何在AngularJS中将模块和服务动态注入到应用程序和控制器中?

[英]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? 启动我的角度应用程序后,如何向myApp添加模块?

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. 我知道可以仅使用内联数组注释添加所有模块,然后仅在控制器内部检查myService是否存在。 But I'm trying to do this the correct way, instead of having to check for myService, thought-out my whole code base. 但是我正在尝试以正确的方式执行此操作,而不是必须检查myService,而无需考虑整个代码库。

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"]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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