2011-06-06 15:50:35 +00:00
|
|
|
|
@ngdoc overview
|
|
|
|
|
|
@name Developer Guide: DI: Using DI in Controllers
|
|
|
|
|
|
@description
|
|
|
|
|
|
|
|
|
|
|
|
The most common place to use dependency injection in angular applications is in {@link
|
|
|
|
|
|
dev_guide.mvc.understanding_controller controllers}. Here is a simple example:
|
|
|
|
|
|
|
|
|
|
|
|
<pre>
|
2012-03-23 23:54:48 +00:00
|
|
|
|
function MyController($location){
|
|
|
|
|
|
// do stuff with the $location service
|
2011-06-06 15:50:35 +00:00
|
|
|
|
}
|
2012-03-23 23:54:48 +00:00
|
|
|
|
MyController.$inject = ['$location'];
|
2011-06-06 15:50:35 +00:00
|
|
|
|
</pre>
|
|
|
|
|
|
|
|
|
|
|
|
In this example, the `MyController` constructor function takes one argument, the {@link
|
2012-03-23 23:54:48 +00:00
|
|
|
|
api/angular.module.ng.$location $location} service. Angular is then responsible for supplying the
|
|
|
|
|
|
instance of `$location` to the controller when the constructor is instantiated. There are two ways
|
|
|
|
|
|
to cause controller instantiation – by configuring routes with the `$location` service, or by
|
|
|
|
|
|
referencing the controller from the HTML template, as follows:
|
2011-06-06 15:50:35 +00:00
|
|
|
|
|
|
|
|
|
|
<pre>
|
|
|
|
|
|
<!doctype html>
|
2012-03-14 06:00:30 +00:00
|
|
|
|
<html ng-controller="MyController" ng-app>
|
2012-01-07 02:10:47 +00:00
|
|
|
|
<script src="http://code.angularjs.org/angular.min.js"></script>
|
2011-06-06 15:50:35 +00:00
|
|
|
|
<body>
|
|
|
|
|
|
...
|
|
|
|
|
|
</body>
|
|
|
|
|
|
</html>
|
|
|
|
|
|
</pre>
|
|
|
|
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
|
|
|
<pre>
|
2012-03-23 23:54:48 +00:00
|
|
|
|
MyController.$inject = ['$location'];
|
2011-06-06 15:50:35 +00:00
|
|
|
|
</pre>
|
|
|
|
|
|
|
|
|
|
|
|
The information in `$inject` is then used by the {@link api/angular.injector injector} to call the
|
|
|
|
|
|
function with the correct arguments.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
## Related Topics
|
|
|
|
|
|
|
|
|
|
|
|
* {@link dev_guide.di About Dependency Injection}
|
|
|
|
|
|
* {@link dev_guide.di.understanding_di Understanding Dependency Injection in Angular}
|
|
|
|
|
|
* {@link dev_guide.services Angular Services}
|
|
|
|
|
|
|
|
|
|
|
|
## Related API
|
|
|
|
|
|
|
|
|
|
|
|
* {@link api/angular.injector Angular Injector API}
|