Dependency Injection

In order to make our application testable and well-designed, we need to make our components flexible which are related to each other. It is known as coupling in the object-oriented world, and indicates the level of dependency between the components.

We need to be careful about using the operator 'new' inside a component. It reduces the chances of replacing the dependency, making it difficult for us to test it.

AngularJS is powered by a dependency injection mechanism that manages the life cycle of each component. This mechanism is responsible for creating and distributing the components within the application.

The easiest way to obtain a dependency inside a component is by just declaring it as a parameter. The framework's dependency injection mechanism ensures that it will be injected properly.

Injecting parameters in controller
In the following code, the controller is injected with two injected parameters, $scope and $filter:

controllers.js
parking.controller("parkingCtrl", function ($scope, $filter) {
$scope.appTitle = $filter("uppercase")("Parking");
});
The above code will not work properly after the code is minified and obfuscated (algorithm which is used to reduce the amount of code by removing whitespaces, comments, and newline characters, and also renaming local variables).

The following code is an example of our previous code after it is minified and obfuscated.

controllers.min.js
x.controller("parkingCtrl", function(a, b) {
a.appTitle = b("uppercase")
("Parking");
});
The $scope and $filter parameters were renamed arbitrarily. In this case, the framework will throw the following error, indicating that the required service provider could not be found
Error: [$injector:unpr] Unknown provider: aProvider <- a

Because of problem after minified or obfuscated, the most recommended way to use the dependency injection mechanism, is through the inline array annotation, as follows.
parking.controller("parkingCtrl", ["$scope", "$filter", function($scope, $filter) {
$scope.appTitle = $filter("uppercase")("Parking");
}]);
The correct dependency will be injected by declaring this way, even after the minify and obfuscate the code and no doesn't matters the name of each parameter.

The dependencies can also be injected in the same way inside directives, filters, and services.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +