16.07.2017 Views

AngularJS Essentials

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Because of this, the most recommended way to use the dependency injection<br />

mechanism, despite verbosity, is through the inline array annotation, as follows:<br />

parking.controller("parkingCtrl", ["$scope", "$filter", function<br />

($scope, $filter) {<br />

$scope.appTitle = $filter("uppercase")("[Packt] Parking");<br />

}]);<br />

This way, no matter what the name of each parameter is, the correct dependency<br />

will be injected, resisting the most common algorithms that minify and obfuscate<br />

the code.<br />

Chapter 4<br />

The dependencies can also be injected in the same way inside directives, filters, and<br />

services. Later, in Chapter 7, Unit Testing, we are going to learn other strategies in<br />

order to inject dependencies for testing purposes.<br />

In the following sections, we are going to use these concepts in greater detail while<br />

using and creating services.<br />

Creating services<br />

In <strong>AngularJS</strong>, a service is a singleton object that has its life cycle controlled by the<br />

framework. It can be used by any other component such as controllers, directives,<br />

filters, and even other services.<br />

Now, it's time to evolve our application, introducing new features in order to<br />

calculate the parking time and also the price.<br />

To keep high levels of cohesion inside each component, we must take care of what<br />

kind of behavior is implemented in the controller. This kind of feature could be the<br />

responsibility of a service that can be shared across the entire application and also<br />

tested separately.<br />

In the following code, the controller is delegating a specific behavior to the service,<br />

creating a place to evolve the business rules in the future:<br />

controllers.js<br />

parking.controller("parkingCtrl", function ($scope, parkingService) {<br />

$scope.appTitle = "[Packt] Parking";<br />

$scope.cars = [];<br />

$scope.colors = ["White", "Black", "Blue", "Red", "Silver"];<br />

[ 69 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!