Search code examples
angularjsangular-ui-routerangularjs-controlleroclazyload

lazy loaded controller results in error when transitioning to state


Receiving this error...

Error: [ng:areq] Argument 'registerController' is not a function, got undefined

when attempting to transition to a ui-router state...

    .state('register', {
        url: "/register",
        templateUrl: "App/components/register/registerView.html",
        data: { pageTitle: 'Register', specialClass: 'gray-bg' },
        controller: "registerController",
        resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
            loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                // you can lazy load files for an existing module
                return $ocLazyLoad.load(['App/components/register/registerController.js']);
            }]
        }
    })

The lazy loaded file is retrieved and run, here it is for information.

var app = angular.module('application')

function registerController($scope) {
    $scope.test = "test";
};

app.controller('registerController', registerController);

The exception is thrown when the state tries to resolve the

controller: "registerController",

property. But I know that the lazy loaded code has been run at this point and that "registerController" has been registered as a controller.


Solution

  • So, it turns out you can't do this. Registering controllers in the manner above only works at bootstrap.

    But you can do it if you stash a reference to the $controllerProvider register function at config

    app.config(function ($controllerProvider) {
        app.lazy = {
            controller: $controllerProvider.register,
        };
    }
    

    and then in your controller js add the controller using the reference to the register function..

    var app = angular.module('application')
    
    function registerController($scope) {
    
    };
    
    app.lazy.controller('registerController', ['$scope' ,registerController]);