gilamran
gilamran

Reputation: 7294

How can I get a list of available modules in AngularJS?

When defining an Angular module I define what are my dependencies like this: var myModule = angular.module("MyModuleName", ["Dep1", "Dep2", "Dep3"]);

Each dependency has its own dependencies, directives, controllers etc.

Is there a way to ask AngularJS what are the available injectables? Without instantiating them, just getting a list.

The Angular.$injector only has a "get" method, but this means that I'll instantiate it.

Thanks Gil Amran

Upvotes: 3

Views: 1033

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32367

Actually that's kind of a hack , so only use it for testing and learning purposes!!

All the $injector DI magic is kept inside this file:

https://github.com/angular/angular.js/blob/v1.2.7/src/auto/injector.js

see the createInjector function (line 598 : angularjs 1.2.7)

  • The providerCache variable is the container off what's available to $injector in config blocks.
  • The instanceCache variable is the container off what's available to $injector in all other blocks.
function createInjector(modulesToLoad) {
  var INSTANTIATING = {},
      providerSuffix = 'Provider',
      path = [],
      loadedModules = new HashMap(),
      providerCache = {
        $provide: {
            provider: supportObject(provider),
            factory: supportObject(factory),
            service: supportObject(service),
            value: supportObject(value),
            constant: supportObject(constant),
            decorator: decorator
          }
      },
      providerInjector = (providerCache.$injector =
          createInternalInjector(providerCache, function() {
            throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
          })),
      instanceCache = {},
      instanceInjector = (instanceCache.$injector =
          createInternalInjector(instanceCache, function(servicename) {
            var provider = providerInjector.get(servicename + providerSuffix);
            return instanceInjector.invoke(provider.$get, provider);
          }));

Those variables are well encapsulated inside that closure and you cannot get them from outside.

unless you add these two lines to the createInjector function:

window.providerCache = providerCache;
window.instanceCache = instanceCache;

How to use it:

Upvotes: 3

Related Questions