forked from angular/code.angularjs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdev_guide.di.using_di_controllers.html
41 lines (37 loc) · 2.45 KB
/
dev_guide.di.using_di_controllers.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<h1>Developer Guide: DI: Using DI in Controllers</h1>
<div class="developer-guide-di-using-di-in-controllers"><fieldset class="workInProgress"><legend>Work in Progress</legend>
This page is currently being revised. It might be incomplete or contain inaccuracies.</fieldset>
<p>The most common place to use dependency injection in angular applications is in <a href="#!/guide/dev_guide.mvc.understanding_controller">controllers</a>. Here is a simple example:</p><div ng:non-bindable><pre class="brush: js;">
function MyController($route){
// configure the route service
$route.when(...);
}
MyController.$inject = ['$route'];
</pre></div><p>In this example, the <code>MyController</code> constructor function takes one argument, the <a href="#!/api/angular.service.$route"><code>$route</code></a> service. Angular is then responsible for supplying the instance
of <code>$route</code> to the controller when the constructor is instantiated. There are two ways to cause
controller instantiation – by configuring routes with the <code>$route</code> service, or by referencing the
controller from the HTML template, as follows:</p><div ng:non-bindable><pre class="brush: js; html-script: true;">
<!doctype html>
<html xmlns:ng="http://angularjs.org" ng:controller="MyController">
<script src="http://code.angularjs.org/angular.min.js" ng:autobind></script>
<body>
...
</body>
</html>
</pre></div><p>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 <code>$inject</code>. Think of it as annotations for JavaScript.</p><div ng:non-bindable><pre class="brush: js;">
MyController.$inject = ['$route'];
</pre></div><p>The information in <code>$inject</code> is then used by the <a href="#!/api/angular.injector"><code>injector</code></a> to call the
function with the correct arguments.</p>
<h3>Related Topics</h3>
<ul>
<li><a href="#!/guide/dev_guide.di">About Dependency Injection</a></li>
<li><a href="#!/guide/dev_guide.di.understanding_di">Understanding Dependency Injection in Angular</a></li>
<li><a href="#!/guide/dev_guide.services">Angular Services</a></li>
</ul>
<h3>Related API</h3>
<ul>
<li><a href="#!/api/angular.injector"><code>Angular Injector API</code></a></li>
</ul></div>