3

I need to load controllers dynamically from certain directories, i.e. instead of this:

$routeProvider.when(path, {
    templateUrl: 'templates' + path + '.html',
    controller: 'myController'
});

the directory where it is placed should be pointed:

$routeProvider.when(path, {
    templateUrl: 'templates' + path + '.html',
    controller: 'controllerDir/myController'
});

I guess there should be a some standard approach for it(?). May be there is some way to use dynamically loading file containing the controller similar to the qQuery fashion (getScript)?

3 Answers 3

2

To dynamically load controllers, you need to use RequireJS.

http://requirejs.org/

There is an util that will make it easier to integrate RequireJS to AngularJS app

https://github.com/marcoslin/angularAMD

Sign up to request clarification or add additional context in comments.

Comments

2

Route has a resolve property which can be exploited to achieve dynamic loading of controllers.

This link should get you started:

http://weblogs.asp.net/dwahlin/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs

On a different note, consider this dynamic loading of scripts only when you have lot of controllers. It's better to load scripts upfront (which can be bundled and minified) and have browser cache them to give a smooth experience to users

Comments

0

You can also use this method: https://github.com/kapysh/angular-dynamic-loader

Just grab the directive from that 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
  }
})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.