Improve this Doc View Source $injector

  1. service in module auto

Overview

$injector is used to retrieve object instances as defined by provider, instantiate types, invoke methods, and load modules.

The following always holds true:

var $injector = angular.injector();
expect($injector.get('$injector')).toBe($injector);
expect($injector.invoke(function($injector) {
  return $injector;
})).toBe($injector);

Injection Function Annotation

JavaScript does not have annotations, and annotations are needed for dependency injection. The following are all valid ways of annotating function with injection arguments and are equivalent.

// inferred (only works if code not minified/obfuscated)
$injector.invoke(function(serviceA){});

// annotated
function explicit(serviceA) {};
explicit.$inject = ['serviceA'];
$injector.invoke(explicit);

// inline
$injector.invoke(['serviceA', function(serviceA){}]);

Inference

In JavaScript calling toString() on a function returns the function definition. The definition can then be parsed and the function arguments can be extracted. This method of discovering annotations is disallowed when the injector is in strict mode. NOTE: This does not work with minification, and obfuscation tools since these tools change the argument names.

$inject Annotation

By adding an $inject property onto a function the injection parameters can be specified.

Inline

As an array of injection names, where the last item in the array is the function to call.

Methods

  • get(name, [caller]);

    Return an instance of the service.

    Parameters

    Param Type Details
    name string

    The name of the instance to retrieve.

    caller
    (optional)
    string

    An optional string to provide the origin of the function call for error messages.

    Returns

    *

    The instance.

  • invoke(fn, [self], [locals]);

    Invoke the method and supply the method arguments from the $injector.

    Parameters

    Param Type Details
    fn function()Array.<(string|function())>

    The injectable function to invoke. Function parameters are injected according to the $inject Annotation rules.

    self
    (optional)
    Object

    The this for the invoked method.

    locals
    (optional)
    Object

    Optional object. If preset then any argument names are read from this object first, before the $injector is consulted.

    Returns

    *

    the value returned by the invoked fn function.

  • has(name);

    Allows the user to query if the particular service exists.

    Parameters

    Param Type Details
    name string

    Name of the service to query.

    Returns

    boolean

    true if injector has given service.

  • instantiate(Type, [locals]);

    Create a new instance of JS type. The method takes a constructor function, invokes the new operator, and supplies all of the arguments to the constructor function as specified by the constructor annotation.

    Parameters

    Param Type Details
    Type Function

    Annotated constructor function.

    locals
    (optional)
    Object

    Optional object. If preset then any argument names are read from this object first, before the $injector is consulted.

    Returns

    Object

    new instance of Type.

  • annotate(fn, [strictDi]);

    Returns an array of service names which the function is requesting for injection. This API is used by the injector to determine which services need to be injected into the function when the function is invoked. There are three ways in which the function can be annotated with the needed dependencies.

    Argument names

    The simplest form is to extract the dependencies from the arguments of the function. This is done by converting the function into a string using toString() method and extracting the argument names.

    // Given
    function MyController($scope, $route) {
      // ...
    }
    
    // Then
    expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
    

    You can disallow this method by using strict injection mode.

    This method does not work with code minification / obfuscation. For this reason the following annotation strategies are supported.

    The $inject property

    If a function has an $inject property and its value is an array of strings, then the strings represent names of services to be injected into the function.

    // Given
    var MyController = function(obfuscatedScope, obfuscatedRoute) {
      // ...
    }
    // Define function dependencies
    MyController['$inject'] = ['$scope', '$route'];
    
    // Then
    expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
    

    The array notation

    It is often desirable to inline Injected functions and that's when setting the $inject property is very inconvenient. In these situations using the array notation to specify the dependencies in a way that survives minification is a better choice:

    // We wish to write this (not minification / obfuscation safe)
    injector.invoke(function($compile, $rootScope) {
      // ...
    });
    
    // We are forced to write break inlining
    var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
      // ...
    };
    tmpFn.$inject = ['$compile', '$rootScope'];
    injector.invoke(tmpFn);
    
    // To better support inline function the inline annotation is supported
    injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
      // ...
    }]);
    
    // Therefore
    expect(injector.annotate(
       ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
     ).toEqual(['$compile', '$rootScope']);
    

    Parameters

    Param Type Details
    fn function()Array.<(string|function())>

    Function for which dependent service names need to be retrieved as described above.

    strictDi
    (optional)
    boolean

    Disallow argument name annotation inference.

    (default: false)

    Returns

    Array.<string>

    The names of the services which the function requires.

  • loadNewModules([mods]);

    This is a dangerous API, which you use at your own risk!

    Add the specified modules to the current injector.

    This method will add each of the injectables to the injector and execute all of the config and run blocks for each module passed to the method.

    If a module has already been loaded into the injector then it will not be loaded again.

    • The application developer is responsible for loading the code containing the modules; and for ensuring that lazy scripts are not downloaded and executed more often that desired.
    • Previously compiled HTML will not be affected by newly loaded directives, filters and components.
    • Modules cannot be unloaded.

    You can use $injector.modules to check whether a module has been loaded into the injector, which may indicate whether the script has been executed already.

    Parameters

    Param Type Details
    mods
    (optional)
    Array<String|Function|Array>=

    an array of modules to load into the application. Each item in the array should be the name of a predefined module or a (DI annotated) function that will be invoked by the injector as a config block. See: modules

    Example

    Here is an example of loading a bundle of modules, with a utility method called getScript:

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

Properties

  • modules

    A hash containing all the modules that have been loaded into the $injector.

    You can use this property to find out information about a module via the myModule.info(...) method.

    For example:

    var info = $injector.modules['ngAnimate'].info();
    

    Do not use this property to attempt to modify the modules after the application has been bootstrapped.

© 2010–2020 Google, Inc.
Licensed under the Creative Commons Attribution License 3.0.
https://code.angularjs.org/1.8.2/docs/api/auto/service/$injector