Previous post we were talking about Dependency Injection in AngularJs so today also talk about AngularJs stuff related to Dependency Annotation.
AngularJs invokes certain services, factories and controllers via the injector. So its a best practices to annotate these functions. it meant that the injector knows what services to inject into the function.
There are three ways of annotating your code with service name information:
- Inline array annotation
- $inject property annotation
- Implicitly from the function parameter name
//define a module var mainApp = angular.module("mainApp", []); mainApp.controller('MathsFunController', ['$scope', 'mathService', function($scope, mathService) { // ... }]);Here we pass an array whose elements consist of a list of strings (the names of the dependencies) followed by the function itself.
When using this type of annotation, take care to keep the annotation array in sync with the parameters in the function declaration.
$inject Property Annotation
$inject To allow the minifiers to rename the function parameters and still be able to inject the right services, so function needs to be annotated with the $inject property.
The $inject property work like array so its hold the service name to inject.
//define a module var mainApp = angular.module("mainApp", []); var MathsFunController = function($scope, mathService) { // ... } MathsFunController.$inject = ['$scope', 'mathService']; mainApp.controller('MathsFunController', MathsFunController);Implicit Annotation
Careful: If you plan to minify your code, your service names will get renamed and break your app.The is the simplest way to inject the dependencies because of dependencies is to assume that the function parameter names are the names of the dependencies.
//define a module var mainApp = angular.module("mainApp", []); mainApp.controller('MathsFunController', function($scope, mathService{ // ... });Above a function, the injector can refer the names of the servies to inject at function declaration and extracting the parameter names.
Given example, $scope and mathService are two services which need to be injected into the function.
One advantage of this approach is that there's no array of names to keep in sync with the function parameters. You can also freely reorder dependencies.
However one disadvantage of this approach will not work with JavaScript minifiers/obfuscators because of how they rename parameters.
So recommend avoiding this approach of annotation.
Hope you get idea about Dependency Annotation in AngularJs.
Please share your suggestions and comment for improvement.
Its usable Good keep it up
ReplyDelete