Dynamic load controllers in AngularJS for routing
I need to dynamically load controllers from specific directories i.e. instead of this:
$routeProvider.when(path, {
templateUrl: 'templates' + path + '.html',
controller: 'myController'
});
the directory it is placed in must be specified:
$routeProvider.when(path, {
templateUrl: 'templates' + path + '.html',
controller: 'controllerDir/myController'
});
I guess there must be some standard approach (?) For it. Maybe there is a way to use a dynamically loaded file containing a controller similar to the qQuery (getScript) way?
source to share
A route has a property resolve
that can be used to achieve dynamic loading of controllers.
This link should help you:
On another note, consider this dynamic script loading only when you have many controllers. Better to download upfront scripts (which can be bundled and miniature) and have browser cache to give users a pleasant experience
source to share
You can also use this method: https://github.com/kapysh/angular-dynamic-loader
Just take the directive from this repo loadctrl.directive.js
and in your template:
<div load-ctrl="portalController"></div>
and in app.js:
portal.constant('CONTROLLER_PATHS', {
'portalController': {
path: 'static/angular_app/js/controllers/portal.controller.js',
loaded: false
}
})
source to share