AngularJS: lazy loading controllers and content

后端 未结 9 864
小鲜肉
小鲜肉 2020-12-02 19:00

In this simplified scenario, I have two files: index.htm, lazy.htm.

index.htm:

var myApp = angular.module(\'myApp\', []);
myApp.controller(\'embed\',         


        
9条回答
  •  情书的邮戳
    2020-12-02 19:29

    At first I utilized André Betiolo's answer. However, it does not always work becasue the ajax loading is non-blocking causing the view to sometimes request the controller prior to the script being loaded.

    As a solution i forced the function not to return until all scripts successfully loaded. This is kind of hackish but makes sure the loads are successful prior to completing the resolve. It also allows for loading of multiple controllers.

    app.js

    var app = angular.module ('app', ['ngRoute']);
    
    app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider){
    
        /*Creating a more synthesized form of service of $ controllerProvider.register*/
        app.registerCtrl = $controllerProvider.register;
    
        //jquery to dynamically include controllers as needed
        function controllers(controllers){
            var numLoaded = 0;
            for (i = 0; i < controllers.length; i++) {
                $.ajaxSetup({async:false});
                $.getScript('js/controllers/' + controllers[i] + '.js').success(function(){
                    numLoaded++;
                    if (numLoaded == controllers.length) {
                        return true; //only return after all scripts are loaded, this is blocking, and will fail if all scripts aren't loaded.
                    }
                });
            }
        }
    
        $routeProvider
            .when('/', {
                templateUrl: 'views/foo.html',
                resolve: {
                    load: function () {
                        controllers(['foo'])
                    }
                }
            })
            .when('/bar',{
                templateUrl: 'views/bar.html',
                controller: 'BarCtrl',
                resolve: {
                    load: function () {
                        controllers(['bar','foo']) //you can load multiple controller files
                    }
                }
            })
            .otherwise({
                redirectTo: document.location.pathname
            });
    }]);
    

    /views/foo.html

    {{text}}

    /views/bar.html

    {{text2}}
    {{text}}

    /controllers/bar.js

    app.registerCtrl('BarCtrl',function($scope){
        $scope.text2 = 'Test';
    });
    

提交回复
热议问题