EVOLUTION-MANAGER
Edit File: step_05.html
<a href='https://github.com/angular/angular.js/edit/v1.3.x/docs/content/tutorial/step_05.ngdoc?message=docs(tutorial%2F5 - XHRs & Dependency Injection)%3A%20describe%20your%20change...' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a> <ul doc-tutorial-nav="5"></ul> <p>Enough of building an app with three phones in a hard-coded dataset! Let's fetch a larger dataset from our server using one of Angular's built-in <a href="guide/services">services</a> called <a href="api/ng/service/$http">$http</a>. We will use Angular's <a href="guide/di">dependency injection (DI)</a> to provide the service to the <code>PhoneListCtrl</code> controller.</p> <ul> <li>There is now a list of 20 phones, loaded from the server.</li> </ul> <div doc-tutorial-reset="5"></div> <h2 id="data">Data</h2> <p>The <code>app/phones/phones.json</code> file in your project is a dataset that contains a larger list of phones stored in the JSON format.</p> <p>Following is a sample of the file:</p> <pre><code class="lang-js">[ { "age": 13, "id": "motorola-defy-with-motoblur", "name": "Motorola DEFY\u2122 with MOTOBLUR\u2122", "snippet": "Are you ready for everything life throws your way?" ... }, ... ] </code></pre> <h2 id="controller">Controller</h2> <p>We'll use Angular's <a href="api/ng/service/$http">$http</a> service in our controller to make an HTTP request to your web server to fetch the data in the <code>app/phones/phones.json</code> file. <code>$http</code> is just one of several built-in <a href="guide/services">Angular services</a> that handle common operations in web apps. Angular injects these services for you where you need them.</p> <p>Services are managed by Angular's <a href="guide/di">DI subsystem</a>. Dependency injection helps to make your web apps both well-structured (e.g., separate components for presentation, data, and control) and loosely coupled (dependencies between components are not resolved by the components themselves, but by the DI subsystem).</p> <p><strong><code>app/js/controllers.js:</code></strong></p> <pre><code class="lang-js">var phonecatApp = angular.module('phonecatApp', []); phonecatApp.controller('PhoneListCtrl', function ($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.orderProp = 'age'; }); </code></pre> <p><code>$http</code> makes an HTTP GET request to our web server, asking for <code>phones/phones.json</code> (the url is relative to our <code>index.html</code> file). The server responds by providing the data in the json file. (The response might just as well have been dynamically generated by a backend server. To the browser and our app they both look the same. For the sake of simplicity we used a json file in this tutorial.)</p> <p>The <code>$http</code> service returns a <a href="api/ng/service/$q">promise object</a> with a <code>success</code> method. We call this method to handle the asynchronous response and assign the phone data to the scope controlled by this controller, as a model called <code>phones</code>. Notice that Angular detected the json response and parsed it for us!</p> <p>To use a service in Angular, you simply declare the names of the dependencies you need as arguments to the controller's constructor function, as follows:</p> <pre><code>phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {...} </code></pre> <p>Angular's dependency injector provides services to your controller when the controller is being constructed. The dependency injector also takes care of creating any transitive dependencies the service may have (services often depend upon other services).</p> <p>Note that the names of arguments are significant, because the injector uses these to look up the dependencies.</p> <p><img class="diagram" src="img/tutorial/tutorial_05.png"></p> <h3 id="-prefix-naming-convention"><code>$</code> Prefix Naming Convention</h3> <p>You can create your own services, and in fact we will do exactly that in step 11. As a naming convention, Angular's built-in services, Scope methods and a few other Angular APIs have a <code>$</code> prefix in front of the name.</p> <p>The <code>$</code> prefix is there to namespace Angular-provided services. To prevent collisions it's best to avoid naming your services and models anything that begins with a <code>$</code>.</p> <p>If you inspect a Scope, you may also notice some properties that begin with <code>$$</code>. These properties are considered private, and should not be accessed or modified.</p> <h3 id="a-note-on-minification">A Note on Minification</h3> <p>Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to <a href="http://goo.gl/SAnnsm">minify</a> the JavaScript code for <code>PhoneListCtrl</code> controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.</p> <p>We can overcome this problem by annotating the function with the names of the dependencies, provided as strings, which will not get minified. There are two ways to provide these injection annotations:</p> <ul> <li><p>Create a <code>$inject</code> property on the controller function which holds an array of strings. Each string in the array is the name of the service to inject for the corresponding parameter. In our example we would write:</p> <pre><code class="lang-js">function PhoneListCtrl($scope, $http) {...} PhoneListCtrl.$inject = ['$scope', '$http']; phonecatApp.controller('PhoneListCtrl', PhoneListCtrl); </code></pre> </li> <li><p>Use an inline annotation where, instead of just providing the function, you provide an array. This array contains a list of the service names, followed by the function itself.</p> <pre><code class="lang-js">function PhoneListCtrl($scope, $http) {...} phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', PhoneListCtrl]); </code></pre> </li> </ul> <p>Both of these methods work with any function that can be injected by Angular, so it's up to your project's style guide to decide which one you use.</p> <p>When using the second method, it is common to provide the constructor function inline as an anonymous function when registering the controller:</p> <pre><code class="lang-js">phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function($scope, $http) {...}]); </code></pre> <p>From this point onward, we're going to use the inline method in the tutorial. With that in mind, let's add the annotations to our <code>PhoneListCtrl</code>:</p> <p><strong><code>app/js/controllers.js:</code></strong></p> <pre><code class="lang-js">var phonecatApp = angular.module('phonecatApp', []); phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', function ($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.orderProp = 'age'; }]); </code></pre> <h2 id="test">Test</h2> <p><strong><code>test/unit/controllersSpec.js</code>:</strong></p> <p>Because we started using dependency injection and our controller has dependencies, constructing the controller in our tests is a bit more complicated. We could use the <code>new</code> operator and provide the constructor with some kind of fake <code>$http</code> implementation. However, Angular provides a mock <code>$http</code> service that we can use in unit tests. We configure "fake" responses to server requests by calling methods on a service called <code>$httpBackend</code>:</p> <pre><code class="lang-js">describe('PhoneCat controllers', function() { describe('PhoneListCtrl', function(){ var scope, ctrl, $httpBackend; // Load our app module definition before each test. beforeEach(module('phonecatApp')); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service in order to avoid a name conflict. beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('phones/phones.json'). respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]); scope = $rootScope.$new(); ctrl = $controller('PhoneListCtrl', {$scope: scope}); })); </code></pre> <p>Note: Because we loaded Jasmine and <code>angular-mocks.js</code> in our test environment, we got two helper methods <a href="api/ngMock/function/angular.mock.module">module</a> and <a href="api/ngMock/function/angular.mock.inject">inject</a> that we'll use to access and configure the injector.</p> <p>We created the controller in the test environment, as follows:</p> <ul> <li><p>We used the <code>inject</code> helper method to inject instances of <a href="api/ng/service/$rootScope">$rootScope</a>, <a href="api/ng/service/$controller">$controller</a> and <a href="api/ng/service/$httpBackend">$httpBackend</a> services into the Jasmine's <code>beforeEach</code> function. These instances come from an injector which is recreated from scratch for every single test. This guarantees that each test starts from a well known starting point and each test is isolated from the work done in other tests.</p> </li> <li><p>We created a new scope for our controller by calling <code>$rootScope.$new()</code></p> </li> <li><p>We called the injected <code>$controller</code> function passing the name of the <code>PhoneListCtrl</code> controller and the created scope as parameters.</p> </li> </ul> <p>Because our code now uses the <code>$http</code> service to fetch the phone list data in our controller, before we create the <code>PhoneListCtrl</code> child scope, we need to tell the testing harness to expect an incoming request from the controller. To do this we:</p> <ul> <li><p>Request <code>$httpBackend</code> service to be injected into our <code>beforeEach</code> function. This is a mock version of the service that in a production environment facilitates all XHR and JSONP requests. The mock version of this service allows you to write tests without having to deal with native APIs and the global state associated with them — both of which make testing a nightmare.</p> </li> <li><p>Use the <code>$httpBackend.expectGET</code> method to train the <code>$httpBackend</code> service to expect an incoming HTTP request and tell it what to respond with. Note that the responses are not returned until we call the <code>$httpBackend.flush</code> method.</p> </li> </ul> <p>Now we will make assertions to verify that the <code>phones</code> model doesn't exist on <code>scope</code> before the response is received:</p> <pre><code class="lang-js">it('should create "phones" model with 2 phones fetched from xhr', function() { expect(scope.phones).toBeUndefined(); $httpBackend.flush(); expect(scope.phones).toEqual([{name: 'Nexus S'}, {name: 'Motorola DROID'}]); }); </code></pre> <ul> <li><p>We flush the request queue in the browser by calling <code>$httpBackend.flush()</code>. This causes the promise returned by the <code>$http</code> service to be resolved with the trained response. See 'Flushing HTTP requests' in the <a href="api/ngMock/service/$httpBackend">mock $httpBackend</a> documentation for a full explanation of why this is necessary.</p> </li> <li><p>We make the assertions, verifying that the phone model now exists on the scope.</p> </li> </ul> <p>Finally, we verify that the default value of <code>orderProp</code> is set correctly:</p> <pre><code class="lang-js">it('should set the default value of orderProp model', function() { expect(scope.orderProp).toBe('age'); }); </code></pre> <p>You should now see the following output in the Karma tab:</p> <pre>Chrome 22.0: Executed 2 of 2 SUCCESS (0.028 secs / 0.007 secs)</pre> <h1 id="experiments">Experiments</h1> <ul> <li><p>At the bottom of <code>index.html</code>, add a <code><pre>{{phones | filter:query | orderBy:orderProp | json}}</pre></code> binding to see the list of phones displayed in json format. </p> </li> <li><p>In the <code>PhoneListCtrl</code> controller, pre-process the http response by limiting the number of phones to the first 5 in the list. Use the following code in the <code>$http</code> callback:</p> <pre><code>$scope.phones = data.splice(0, 5); </code></pre> </li> </ul> <h1 id="summary">Summary</h1> <p>Now that you have learned how easy it is to use Angular services (thanks to Angular's dependency injection), go to <a href="tutorial/step_06">step 6</a>, where you will add some thumbnail images of phones and some links.</p> <ul doc-tutorial-nav="5"></ul>