Answer the question
In order to leave comments, you need to log in
How to dynamically load controllers in AngularJS?
The application has the structure
/app
---/modules
------/moduleName
---------/controllers
------------/controllerName.js Tell me
how best to dynamically load controllers depending on the route?
tried like this
$routeProvider
.when('/:module/:controller/:action', {
templateUrl: function(r) { return modulesPath + '/' + r.module + '/views/' + r.controller + '.html'; },
controller: DynamicController
})
;
function DynamicController()
{
...
return '/app/modules/moduleName/controllers/controllerName.js';
}
Answer the question
In order to leave comments, you need to log in
As far as I understand, you want to define one bold route that will resolve the situation for all controllers. This is fundamentally the wrong approach. Thus, you lose control over the application. The angularjs routing system has a rather powerful thing called resolve-you, which one way or another will only work fine for individual routes.
But still, if your hands itch, you need to dig in the direction of how controllers are loaded by name and rewrite the initialization logic (where the controller is simply taken as a service from the container, as far as I remember) inside ngRoute itself.
Here is an article with examples on this topic:
weblogs.asp.net/dwahlin/dynamically-loading-control...
I really recommend to think several times whether you really need this. I wrote an incredible amount of code in Angular and I have never needed dynamic loading - choosing a controller, even if I needed it, I would choose the controller I need already in the body of the ng-controller template, preloading it in the resolve: route property
So and the code will be more readable - it's immediately clear who goes where and how :-)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question