M
M
Mikhail Osher2013-11-22 19:01:30
Angular
Mikhail Osher, 2013-11-22 19:01:30

How to dynamically load controllers in Angular?

I am using AngularUI Router .
In templates I use the following code:

<section data-ng-controller="FooBarCtrl">
<!-- content -->
</section>

But I want to load the controller dynamically, like this:
// state выглядит примерно так
{name: 'foo', url: '/foo', templateUrl: '/app/views/foo.html', pageTitle: 'Foo', files: {js: ['/app/controllers/foobar.js']}}
// код внутри run()
$rootScope.$on('$stateChangeStart', function(event, state) {
    // тут хочу подгрузить данные из state.files.js
});

But.. it doesn't work that way. Even if not loaded via async, blocking other calls.
Now I compress and compile all js into one file, because in fact the whole application is SPA . And if there are not 4-5 controllers, but 30?
I would like a more elegant solution. Has anyone encountered such a problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
malykhinvi, 2013-11-22
@malykhinvi

In fact, this is not only the task of loading controllers, but also other modules (factories, directives...). When developing the first application in angular, the question of asynchronous loading of components also arose.
There is a great example here .
In general, when configuring an application, we say which modules need to be resolved before going through the route. And dynamic loading falls on the shoulders of RequireJS.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question