There are three distinct approaches to implementing dependency injection in Angular.
Approach 1: Injection array
The injection array syntax provides a clear understanding of the dependencies required for a function to run.
controllerName.$inject = ['$scope', '$http'];
function controllerName($scope, $http) {
// code here
}
Dependency injection simply involves specifying additional properties that inform angular about the necessary services. These services are then passed as arguments to the function based on the strings listed in the injection array. The function's argument names can vary, but they must align with the names in the injection array.
Approach 2: Injectable function
Angular offers a specific syntax for defining injectable functions, such as controllers, services, directives, and component template functions.
['$scope', '$http', function($scope, $http) { // code here }]
This method combines the injection list with the function definition, making it reliable but potentially cluttered as the dependency count increases.
Approach 3: Interpreted Dependency Names
If no explicit method is used, Angular will attempt to infer the required dependencies based on the argument names.
function($scope, $http) { // code here }
While this approach appears straightforward, it is not recommended due to potential issues with minification and confusion over variable naming.
To achieve the cleanliness of Approach 3 combined with the reliability of the first two methods, consider using the post-processing tool NgAnnotate: https://github.com/olov/ng-annotate.