$routeProvider - injecting controller dependencies depending on URL

angularjs, dependency-injection, javascript

Solution

Yes! AngularJS can handle this pretty easily thnx to the `resolve` property of a route definition (more info here).

So, basically you could write something like:

var app = angular.module("app", [], function($routeProvider) {
  $routeProvider
    .when("/page1", { controller: "MyController", resolve: {Strategy: "StrategyOne"}})
    .when("/page2", { controller: "MyController", resolve: {Strategy: "StrategyTwo"}})
    .when("/page3", { controller: "MyController", resolve: {Strategy: "StrategyThree"}});
});

to have the proper strategy injected into your controller! AngularJS DI at its best!

There is a very good video tutorial dealing with the `resolve` topics, you might find it interesting: http://www.youtube.com/watch?v=P6KITGRQujQ&list=UUKW92i7iQFuNILqQOUOCrFw&index=4&feature=plcp

Problem

Consider the code: ``` var app = angular.module("app", [], function($routeProvider) { $routeProvider .when("/page1", { controller: "MyController" }) .when("/page2", { controller: "MyController" }) .when("/page3", { controller: "MyController" }); }); app.factory("StrategyOne", function() {...}); app.factory("StrategyTwo", function() {...}); app.factory("StrategyThree", function() {...}); app.controller("MyController", function(Strategy, $scope) {...}); ``` Depending on URL, I want either `StrategyOne`, or `StrategyTwo`, or `StrategyThree` to be injected, when constructing `MyController`. A pseudo-code to illustrate the idea: ``` var app = angular.module("app", [], function($routeProvider) { $routeProvider .when("/page1", { controller: "MyController", Strategy: "StrategyOne" }) .when("/page2", { controller: "MyController", Strategy: "StrategyTwo" }) .when("/page3", { controller: "MyController", Strategy: "StrategyThree" }); }); ``` Any change I can achieve something like this with AngularJS?

Original source