Angular allows you to load templates by router means dynamically, but so far I have not found a single example where the controller would dynamically load also ...

var app = angular.module( 'app', ['ngRoute'] ); app.config([ '$routeProvider', function( $routeProvider ) { $routeProvider .when('/', { templateUrl: 'template/main/main.html', controller: 'MainCtr' }) .when('/login', { templateUrl: 'template/only/login.html', controller: 'LoginCtr' }) .otherwise({ redirectTo: '/' }); } ]); 

How to load controllers dynamically with loading a template? For example, if the controller script is in the same folder with the template. Or is the 'standard' router not suitable for these purposes?

  • one
    Maybe this will help. stackoverflow.com/questions/20909525/… . - diproart
  • What code is in question? It works fine and sets the controller to the selected view. Did you want something else? - Grundy
  • It requires the pre-connection of scripts, and it was necessary that they stretched as well as the templates - dynamically, as needed. - t1nk

1 answer 1

For this task, I have adopted a webpack , ui-router and oclazyload

Set up a webpack broken down by chunks. You can see a good screencast , which will give full information about setting up

 output: { path: path.resolve(__dirname, 'web/'), publicPath: '/', chunkFilename: 'js/bundle.[name].js', filename: 'js/bundle.js' }, 

An example of routing.

 { stateName: 'app.articles.detail', params: { url: '/:code', templateProvider: ($q) => { return $q((resolve) => { require.ensure([], () => resolve(require('./views/articles.detail.html'))); }); }, controller: 'ArticlesDetailController as vm', resolve: { loadArticlesDetailController: ($q, $ocLazyLoad) => { return $q((resolve) => { require.ensure([], () => { // load only controller module let module = require('./controllers/articles.detail.controller'); $ocLazyLoad.load({ name: module.name }); resolve(module.controller); }) }); } } } } 

Webpack will create separate bundles for the template and the controller and load them dynamically.

Will load them only if necessary.