The first approach uses dependency injection, and the second uses a service locator pattern. Dependency injection has the following advantages:
It makes components explicitly dependent. For example, you can look at the controller constructor function and immediately find out what dependencies it needs. Using a service locator, you usually donβt know, because the controller can refer to the service locator every time.
This makes unit test easier. For example, you can use the $controller service to instantiate a controller and feed it with mock objects using the locals argument. This is certainly easier than defining a bunch of AngularJS services or factories so that $injector can resolve them. When combined, C # 1 gets worse: you may not be aware of all the dependencies a component requires to provide all the necessary layouts.
The service locator offers some flexibility. For example, your code can only use the service if it exists, for example:
if ($injector.has('serviceA')) $injector.get('serviceA').doSomething() else someSomethingElse()
When dependencies are introduced, if serviceA does not exist at the time your component was created, you will receive an error message.
As for the convenience of refactoring, I donβt think itβs difficult to add / remove parameters to the constructor function. As pointed out in the commentary on your question, tools like ngAnnotate will help make the announcement DRYer.
Therefore, I would just stick with dependency injection and use only the service locator when it is absolutely necessary.
source share