Injecting modules after lazy loading

1.9k views Asked by At

I a have a chase where I have large application and in an attempt to keep the size of it down I am trying to lazily load submodules and their associated assets. I am using ocLazyLoad to lazyLoad the modules and their files.

However, after a module is loaded none of it dependencies seem to get registered into the application, so services and directives the lazily loaded submodule depend on are not loaded resulting in things not looking the way they should.

This plunk provides a minimal example.

//lazilyLoaded.module.js
angular.module('lazyLoadedModule', 
  ['orginallyIncludedModule'])
  .run(function(){
    console.log('lazyLoadedModule ran');
  });

//script.js
angular.module('app', ['oc.lazyLoad']).config(['$ocLazyLoadProvider', 

function($ocLazyLoadProvider) {
  $ocLazyLoadProvider.config({
    debug: true,
    modules: [{
      name: 'lazyLoadedModule',
      files: ['lazyLoaded.module.js']
    }]
  });
}]).run(function($ocLazyLoad){
  $ocLazyLoad.load('lazyLoadedModule');
});
//script.js
angular.module('orginallyIncludedModule', [])
  .run(function(){
    console.log('originallyIncludedModule ran');
  })
  .directive('simpleDirective', function(){
    return {
      template: '<p>All is well</p>'
    };
  })
1

There are 1 answers

0
toxaq On

There's a couple of things going on here. First is that you need to wait until the module is loaded before attempting to use it but also secondly you need to tell the page that a new directive is available. This isn't well documented but is in the FAQS.

I lazy-loaded a directive but nothing changed on my page If the directive was in your DOM before you lazy-loaded its definition, you need to tell Angular that it should parse the DOM to recompile the new directive. To do that you need to use $compile :

Here's how I changed your run method

run(function($ocLazyLoad, $compile, $rootScope, $document){
  $ocLazyLoad.load('lazyLoadedModule').then(function() {
    $compile($document[0].body)($rootScope);
  });
});

This causes your directive to run. Accessing the DOM in the run method is not very angular, so the above is a bit of hack but at least gets you started.