AngularJS - Injectors

The initial setup:

<div ng-app="app" ng-controller="AppCtrl">
  {{ title }}
</div>
var app = angular.module("app",[]);

app.factory("game", function () {
  return {
    title: "StarCraft"
  };
});

angular.injector(["app"]).invoke(function (game) {
  alert(game.title);
});

app.controller("AppCtrl", function ($scope, game) {
  $scope.title = game.title;
});

Here, the invoke method called on the angular.injector() is a literal demonstration of what is happening behind the scenes with things like the game parameter to the controller. The injector is able to seek out what ‘game’ is being injected as, here a factory.

In invoke(), the key ‘game’, and Angular searches for services with that name. Ultimately, the cache stores all providers, so invoke checks there. The injector grabs the provider and throws it into that function. Instead of calling invoke() on app.injector(), It is also possible, though not practical, to inject the $injector service into the controller instead of services:

app.controller("AppCtrl", function ($scope, $injector) {
  $injector.invoke(function (game) {
    alert(game.title);
    $scope.title = game.title;
  });
});

The $injector service can have invoke() called in the same way, and our access to the game service is unchanged.