The use case is simple: I have two controllers sharing the same dependency MyService. This service is holding some state, lets sat myVariable. If I set it from ControllerOne, then it will be also spotted by ControllerTwo.
What I want is for each controller to have it’s own instance of MyService, so that myVariable can be changed by each Controller without affecting the other.
To put it in another words – I want new instance to be returned by Dependency Injection, rather than singleton.
Not as directly has you might hope. Service instances are created the first time they’re retrieved by the injector and maintained by the injector… in other words, they’re always singletons. The magic happens in here, particularly look at the
providerfunction, which puts the provider instance in the providerCache object.But don’t lose hope, you could just as easily add constructors for whatever it is you want to share in a Service, if you so chose:
EDIT: as the OP pointed out, there is also the $injector.instantiate, which you can use to call JavaScript constructors outside of your controller. I’m not sure what the implications are of the testability here, but it does give you another way to inject code that will construct a new object for you.