Reputation: 5909
I want to dynamically inject a factory into my Angular controller based on the route parameter. This is my route configuration:
$routeProvider
.when("/tables/:table",
{
controller: "tableController",
templateUrl: "/app/views/table.html",
resolve: {
"factory": function r($route) {
return $injector.get($route.current.params.table + "Factory"); // Error!
}
}
})
For instance, when the route is tables/employee
, I want an employeeFactory
to be injected into tableController
, and so on.
Unfortunately, this configuration does not work — I am getting an Unknown provider: employeeFactory
error in the r
function.
On the other hand, I can instead pass an $injector
service directly to the tableController
and successfully resolve employeeFactory
there:
(function (angular) {
var tableController = function ($routeParams, $injector) {
// employeeFactory resolves successfully here!
var factory = $injector.get($routeParams.table + "Factory");
};
angular.module("appModule").controller("tableController", tableController);
})(angular);
However, I do not like this approach because it follows the service locator anti-pattern. I would really like factory
to be injected using routing configuration and not this ugly workaround.
So, why Angular is throwing an error when using $injector.get()
with resolve
, but successfully resolves the factory inside of the tableController
? I am using Angular 1.4.4.
Upvotes: 0
Views: 194
Reputation: 223104
You apparently use $injector
that was injected into config
block, and it differs from $injector
that is injected anywhere else. The former acts on service providers, the latter acts on service instances.
It should be
"factory": function r($route, $injector) {
return $injector.get($route.current.params.table + "Factory");
}
Upvotes: 1