How does dependency injection work in AngularJS?
Quick Answer
AngularJS injects services by matching the parameter name to a registered provider — function(\$http, myService) {}. Because minification renames parameters, you must use the array annotation (['$http', 'myService', function($http, myService){}]) or $inject, or run ng-annotate in the build.
AngularJS looks at the names of your function's parameters and injects the matching registered service — so function($http, orderService) gets those two. That's elegant until you minify the code, because the minifier renames the parameters to single letters and now the injector is looking for services called a and b. The fix is the array annotation, where you list the service names as strings before the function, or you run ng-annotate in your build to add them automatically. The newer Angular fixed this by using explicit type tokens instead of parameter names.
- Registered things:
value,constant,factory,service,provider— all injectable. - The injector resolves the whole dependency graph and caches singletons.
- Minification bug:
function(a, b)→ the injector looks for services namedaandb. Always annotate. - Angular (2+) moved to explicit token-based DI to remove this fragility.