I am currently using require.js and angular. Since I have a very long list of custom views, each for a different task, I've cooked up a way of including them dynamically using requirejs.
First a list of tasks is defined, which is provided as a constant. Then for each of the available tasks the file is required using require.js and the controller subsequently registered to the app by using the angular injector.
Then for each of the tasks a route is added to the route provider (namespaced on a workflow).
var tasks = {
'available' : [
{ id: "choose-problem",
controller: "ChooseProblemController",
templateUrl: "chooseProblem.html" },
{ id: "choose-method",
controller: 'ChooseMethodController',
templateUrl: 'chooseMethod.html' },
]};
app.constant('Tasks', tasks);
_.each(tasks.available, function(task) {
var camelCase = function (str) { return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); };
app.controller(task.controller, ['$scope', '$injector', function($scope, $injector) {
require(['controllers/' + camelCase(task.id)], function(controller) {
$injector.invoke(controller, this, { '$scope' : $scope });
});
}]);
});
// example url: /#/workspaces/<id>/<taskname>
app.config(['Tasks', '$routeProvider', function(Tasks, $routeProvider) {
var baseTemplatePath = "app/partials/tasks/";
_.each(Tasks.available, function(task) {
var templateUrl = baseTemplatePath + task.templateUrl;
$routeProvider.when('/workspaces/:workspaceId/' + task.id, { templateUrl: templateUrl, controller: task.controller });
});
$routeProvider.otherwise({redirectTo: 'workspaces/new/choose-problem'});
}]);
Now I'd like to access the conceptual "current tasks" in a different (parent) controller, so I was thinking of using the route provider is a fashion like this:
app.config(['Tasks', '$routeProvider', function(Tasks, $routeProvider) {
$routeProvider.when('/workspaces/:workspaceId/:task', .... load the controller based on :task
});
}]);
``` As then the task id would be clearly visible in the $routeParams, and thus avoiding some service to expose shared state. Is this possible?