Developer Guide: DI: Using DI in Controllers

The most common place to use dependency injection in angular applications is in controllers. Here is a simple example:

function MyController($route){
 // configure the route service
 $route.when(...);
}
MyController.$inject = ['$route'];

In this example, the MyController constructor function takes one argument, the $route service. Angular is then responsible for supplying the instance of $route to the controller when the constructor is instantiated. There are two ways to cause controller instantiation – by configuring routes with the $route service, or by referencing the controller from the HTML template, as follows:

<!doctype html>
<html ng-controller="MyController" ng-app>
<script src="http://code.angularjs.org/angular.min.js"></script>
<body>
 ...
</body>
</html>

When angular is instantiating your controller, it needs to know what services, if any, should be injected (passed in as arguments) into the controller. Since there is no reflection in JavaScript, we have to supply this information to angular in the form of an additional property on the controller constructor function called $inject. Think of it as annotations for JavaScript.

MyController.$inject = ['$route'];

The information in $inject is then used by the injector to call the function with the correct arguments.

Related Topics

Related API