15

I read a lot about lazzy loading, but I am facing a problem when using $routeProvider.

My goal is to load a javascript file which contains a controller and add a route to this controller which has been loaded previously.

Content of my javascript file to load

angular.module('demoApp.modules').controller('MouseTestCtrlA', ['$scope', function ($scope) {
    console.log("MouseTestCtrlA");
    $scope.name = "MouseTestCtrlA";
}]);

This file is not included when angular bootstap is called. It means, I have to load the file and create a route to this controller.

First, I started writing a resolve function which has to load the Javascript file. But declaring my controller parameter in route declaration gave me an error :

'MouseTestCtrlA' is not a function, got undefined

Here is the call I am trying to set :

demoApp.routeProvider.when(module.action, {templateUrl: module.template, controller: module.controller, resolve : {deps: function() /*load JS file*/} });

From what I read, the controller parameter should be a registered controller

controller – {(string|function()=} – Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.

So I write a factory which should be able to load my file and then (promise style!) I whould try to declare a new route.

It gave me something like below where dependencies is an array of javascript files' paths to load :

Usage

ScriptLoader.load(module.dependencies).then(function () {
    demoApp.routeProvider.when(module.action, {templateUrl: 'my-template', controller: module.controller});
});

Script loader

angular.module('demoApp.services').factory('ScriptLoader', ['$q', '$rootScope', function ($q, $rootScope) {
        return {
            load: function (dependencies)
            {
                var deferred = $q.defer();
                require(dependencies, function () {
                    $rootScope.$apply(function () {
                        deferred.resolve();
                    });
                });
                return deferred.promise;
            }
        }
    }]);

Problem

I still have this javascript error "'MouseTestCtrlA' is not a function, got undefined" which means Angular could not resolved 'MouseTestCtrlA' as a registered controller.

Can anyone help me on this point please ?

4

1 回答 1

26

重读这篇文章http://ify.io/lazy-loading-in-angularjs/建议$contentProvider在 Angular App 中保留一个实例。

我在我的 app.js 中提出了这段代码

demoApp.config(function ($controllerProvider) {
     demoApp.controller = $controllerProvider.register;
});

它使我能够在外部 javascript 文件中按预期编写控制器:

angular.module("demoApp").controller('MouseTestCtrlA', fn);

希望这可以帮助!

于 2013-07-16T11:34:08.310 回答