0

Within my Angular App I want to inject two modules into my App through dependency injection. So:

var App = angular.module('App', ['ngModule1', 'ngModule2']);

var module1 = angular.module('ngModule1', ['App']);
var module2 = angular.module('ngModule2', ['App']);

However what if module2 doesn't exist yet or is not properly instantiated. I want to do something like this:

 var App = angular.module('App', ['ngModule1']);

   //Test if module2 exists
    try {
        var temp = $injector.get('ngModule2');
    } catch (e) {
        console.log('Injector does not have Module 2!');
    }

 //Do something with temp to add it in App

The method above isn't valid but I want to know the proper way to add in a module after testing if it exists

2
  • $injector.get is not for getting a module, it is for getting a factory etc..registered in the loaded module. I think what you need is manual bootstrapping. Commented Jul 30, 2015 at 17:57
  • @PSL I never did inject modules before so that is why I said the above code isn't valid. I know how to inject services but not modules Commented Jul 30, 2015 at 17:58

1 Answer 1

2

It is possible to test and add it.

var modules = ['existingModule', 'nonexistentModule'].filter(function (module) {
  try {
    return !!angular.module(module);    
  } catch (e) {}
});

angular.module('module', modules);

It is also possible to redefine module, but do it before you defined its components and bootstrapped it.

var app;

try {
    app = angular.module('app', ['existingModule', 'debatableModule']);
} catch (e) {
    app = angular.module('app', ['existingModule']);
}

But it may (and most probably does) indicate that something is wrong with app design.

$injector doesn't serve this purpose and it can't help to 'inject' a module into existing one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.