A
A
Abc Edc2015-05-15 10:17:26
Angular
Abc Edc, 2015-05-15 10:17:26

When is it better to use injector and when to just enumerate as a function argument?

in what situations that is

.controller('someCtrl', function($scope,mainService) {
mainService.method().....
})

and when
.controller('someCtrl', function($scope) {
var myInjector = angular.injector(['app']);
 var service = myInjector.get('mainService');
service.method()...
})

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey, 2015-05-15
@gleber1

so, let's start with the fact that there is a $injector service:

function SomeController($injector) {
    var service = $injector.get('mainService');
}

angular.controller('SomeController', ['$injector', SomeController]);

and let's end with the fact that the only two cases when you may need an injector:
- resolving cyclic dependencies, which in itself is a sign of bad architecture but sometimes happens
- creating mini-services on the fly, for example, registering through a provider of handlers and callbacks that want to use services inside.
It is not worth injecting an injector into controllers at all.

_
_ _, 2015-05-15
@AMar4enko

Sergey Protko At the last ngConf there was an example of a controller as an ES6 class, as a preparation for the transition to the 2nd version. In this case, do you propose to shove all used services in this in the constructor? I just save the injector and get everything I need from it along the way.

M
Mikhail Osher, 2015-05-15
@miraage

Essentially, the direct use of the $injector service is the service locatior.
On the Internet, they write a lot, they say this is an anti-pattern, they say it’s bad.
I don't see any reason not to use dependency injection.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question