angularjsdependency-injectionangularjs-moduleoclazyload

Load angular module at runtime with/without ocLazyLoad


I have a couple of modules that I am trying to load at runtime based on some conditions. Currently I am using theocLazyLoad module but I am the loaded module's are not working at all. Everything loads fine, there are no errors being thrown.

I first declare my main module

var app = angular.module('myApp',['oc.lazyLoad'])

app.config(['$ocLazyLoadProvider',function(){
    modules : [{
       name : 'mod1',
       files : [CDN-Path]
     }]
}]);

and then somewhere in my controller

app.controller('c',function($ocLazyLoad){

     $ocLazyLoad.load('mod1').then(function(){
           console.log('module loaded!');
     });
})

What I truly do inside the resolved promise is that I register a new state with ui-router, and within that state I use some of the directives defined in mod1, but they simply don't work. Is there further initialization that must be performed after the module loads?


Solution

  • You can lazy load any module/directive/controller/javascript(jquery as well) before view as below:

    angular.module('app', ['ui.router', 'oc.lazyLoad']).config(['$stateProvider', '$ocLazyLoadProvider', function ($stateProvider, $ocLazyLoadProvider) {
            $ocLazyLoadProvider.config({
                modules : [{
                        name : 'TestModule',
                        files : ['js/TestModule.js', 'js/AppCtrl.js']
                    }
                ]
            });
    
            $stateProvider.state('index', {
                url : "/", // root route
                views : {
                    "lazyLoadView" : {
                        controller : 'AppCtrl', // This view will use AppCtrl loaded below in the resolve
                        templateUrl : 'partials/main.html'
                    }
                },
                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('TestModule');
                        }
                    ]
                }
            });
        }
    ]);
    

    https://oclazyload.readme.io/docs/with-your-router

    Edit Plunker sample with controller and ui-bootstrap lazy loaded : https://plnkr.co/edit/pUq3b1TDkwdGQOftcWDL?p=preview