16.07.2017 Views

AngularJS Essentials

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Dependency Injection and Services<br />

Dependency injection<br />

In order to create testable and well-designed applications, we need to take care about<br />

the way their components are related to each other. This relationship, which is very<br />

famous in the object-oriented world, is known as coupling, and indicates the level of<br />

dependency between the components.<br />

We need to be careful about using the operator new inside a component. It reduces<br />

the chances of replacing the dependency, making it difficult for us to test it.<br />

Fortunately, <strong>AngularJS</strong> is powered by a dependency injection mechanism that<br />

manages the life cycle of each component. This mechanism is responsible for creating<br />

and distributing the components within the application.<br />

The easiest way to obtain a dependency inside a component is by just declaring it as<br />

a parameter. The framework's dependency injection mechanism ensures that it will<br />

be injected properly. In the following code, there is a controller with two injected<br />

parameters, $scope and $filter:<br />

controllers.js<br />

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

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

});<br />

Unfortunately, this approach will not work properly after the code is minified and<br />

obfuscated, which is very common these days. The main purpose of this kind of<br />

algorithm is to reduce the amount of code by removing whitespaces, comments, and<br />

newline characters, and also renaming local variables.<br />

The following code is an example of our previous code after it is minified<br />

and obfuscated:<br />

controllers.min.js<br />

x.controller("parkingCtrl",function(a,b){a.appTitle=b("uppercase")<br />

("[Packt] Parking");});<br />

The $scope and $filter parameters were renamed arbitrarily. In this case, the<br />

framework will throw the following error, indicating that the required service<br />

provider could not be found:<br />

Error: [$injector:unpr] Unknown provider: aProvider

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

Saved successfully!

Ooh no, something went wrong!