Within Angular, is it considered a good practice getting the dependencies directly from an $injector instance, rather than as parameters?
I have the problem that my controllers started having a lot of dependencies, so rather than:
myApp.controller(['$scope', 'Dep1', 'Dep2', 'Dep3', function($scope, Dep1, Dep2, Dep3) {
...
}]);
I would do:
myApp.controller(['$scope', '$injector', function($scope, $injector) {
var Dep1 = $injector.get('Dep1');
var Dep2 = $injector.get('Dep2');
var Dep3 = $injector.get('Dep3');
}]);
I find it the same functionality-wise, but with much less clutter on the parameters. I suppose that this will make my components slightly less easy to test though, right?
What do you think?
Based on my opinion and after reading the following posts:
Post 1
Post 2
Angular's documentation on DI (Dependency Injection)
Your second approach in order to minimize the long dependency list is considered as Service Locator Anti Pattern. See - Service locator AntiPattern
Using the Service Locator Anti Pattern is bad because it will make your life as a maintenance developer worse because you will need to use considerable amounts of brain power to grasp the implications of every change you make. Using the $injector obfuscates the actual dependencies of the resource (in this case controller) and kills maintainability.
In addition, according to angular's documentation the the preferable way is:
Using the inline array annotation (preferred)
If your controller is ending up using so many dependencies maybe you are doing something wrong, Maybe you broke the Single responsibility principle. consider:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With