AngularJS Dependency Injection Injections


The simplest example of an injection in an Angular app - injecting $scope to an Angular Controller:

angular.module('myModule', [])
.controller('myController', ['$scope', function($scope) {
    $scope.members = ['Alice', 'Bob'];

The above illustrates an injection of a $scope into a controller, but it is the same whether you inject any module into any other. The process is the same.

Angular's system is in charge of resolving dependencies for you. If you create a service for instance, you can list it like in the example above and it will be available for you.

You can use DI - Dependency Injection - wherever you are defining a component.

Note that in the above example we use what is called "Inline Array Annotation". Meaning, we explicitly write as strings the names of our dependencies. We do it to prevent the application from breaking when the code is minified for Production. Code minification changes the names of the variables (but not strings), which breaks the injection. By using strings, Angular knows which dependencies we want.

Very important - the order of string names must be the same as the parameters in the function.

There are tools that automate this process and take care of this for you.