Improve this doc

Using services as dependencies for controllers is very similar to using services as dependencies for another service.

Since JavaScript is a dynamic language, DI can't figure out which services to inject by static types (like in static typed languages). Therefore, you can specify the service name by using the $inject property, which is an array containing strings with names of services to be injected. The name must match the corresponding service ID registered with angular. The order of the service IDs matters: the order of the services in the array will be used when calling the factory function with injected parameters. The names of parameters in factory function don't matter, but by convention they match the service IDs, which has added benefits discussed below.

  1. function myController($loc, $log) {
  2. this.firstMethod = function() {
  3. // use $location service
  4. $loc.setHash();
  5. };
  6. this.secondMethod = function() {
  7. // use $log service
  8. $log.info('...');
  9. };
  10. }
  11. // which services to inject ?
  12. myController.$inject = ['$location', '$log'];

Source

  1.  
  1.  
  1.  

Demo

Implicit Dependency Injection

A new feature of Angular DI allows it to determine the dependency from the name of the parameter. Let's rewrite the above example to show the use of this implicit dependency injection of $window, $scope, and our notify service:

Source

  1.  
  1.  

Demo

However, if you plan to minify) your code, your variable names will get renamed in which case you will still need to explicitly specify dependencies with the $inject property.

Related Topics

Understanding Angular Services Creating Angular Services Managing Service Dependencies Testing Angular Services

Related API

Angular Service API