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?

2
  • 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. Commented Mar 22, 2015 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. Commented Mar 22, 2015 at 13:24

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.