3

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?

Preslav Rachev
  • 3,983
  • 6
  • 39
  • 63
  • If you always have to use Dep1,Dep2,Dep3 in multiple controllers. You could create a service that exports those as properties, and then just depend upon that 1 service. – Reactgular Mar 22 '15 at 13:22
  • Testing is a factor. The real issue is that a large number of dependencies often indicates that your controllers are doing too much. What constitutes "large" depends on the individual case. – Cerad Mar 22 '15 at 13:24

2 Answers2

5

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:

  1. Delegate more of the logic to service(s) that are injected in
  2. Separate out into different controllers, so each only has (just about) 1 responsibility
Community
  • 1
  • 1
Or Guz
  • 1,018
  • 6
  • 13
0

It depends how you write the code and how is easy to you and make you flexible to write code. I always write the controllers in this way hope it will help :}

var appCtrl = function($scope, others){...}
app.controller('appCtrl',['$scope', 'others', appCtrl]);
Shaxrillo
  • 769
  • 1
  • 7
  • 24