Girrafish
Girrafish

Reputation: 2482

AngularJS - Inject $factory into controller

I have multiple factories registered, say Circle, Square and Triangle, and a controller called ShapeController. Inside of ShapeController, I'm trying to retrieve one of the factories using its string representation, in the same that I can fetch a controller using $controller('ControllerName', {...}).

var ShapeController = function($scope, $routeParams, $factory) {
  var shape = $factory('Circle', []);  // shape is an instance of the Circle factory
  ....
}

I was hoping I could inject $factory but I keep getting Error: [$injector:unpr] Unknown provider: $factoryProvider <- $factory <- ShapeController. Is there any api or some way I could retrieve the factory?

Upvotes: 3

Views: 368

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

No, you got it wrong. Actually there is nothing called as $factory inbuilt service/provider inside angularjs framework. The thing you mentioned about $controller, its a special provider created by angularjs to instantiate a controller with some local (there you could mock dependencies as well).

As you wanted to grab the instance of particular dependency, you could extract it out from injector(this acts like DI container of DI system), where you should inject $injector dependency inside your controller factory function and use get method to retrieve particular dependency.

var ShapeController = function($scope, $routeParams, $injector) {
  var shape = $injector.get('Circle');
  ....
}

Upvotes: 1

Related Questions