How to load module based on config file in angularJS

I have several specific modules. I don't want to load them all into my application. Instead, I want to load them based on the config file. for example

Module1:

angular.module('section1', [])

      

Module2:

angular.module('section2', [])

      

In each module, it will have its own HTML template and business logic. Then in app.module.js:

angular.module('app', ['module1', 'module2']);

      

module1 and module2 will be loaded together. I don't want to hardcode it, instead I will have a config file like:

[{'module1': true}, {'module2':false}]

      

In the end, every time the application starts, I read the config file and then decide which modules will be loaded and which modules will not. In the example above, module 1 will be loaded and module 2 will not.

How can i do this?

+3


source to share


2 answers


You can manually bootstrap

angular js application. This will help you add conditions and decide which module to load

This is how you do manual upload in angular.



angular.element(function() {
  if(/* condition */ {
    angular.bootstrap(document, ['module1']);
  } else {
    angular.bootstrap(document, ['module2']);
  }
});

      

+1


source


You can create an array of module dependencies before you define your angular module and pass the array as a variable. If you have complete control over the config files and how they are loaded, the config file can be just an array of dependencies. For example:

var config = ['module1', 'module2'];
angular.module('app', config);

      

This assumes you have multiple config files and then load the one you want for that particular context.



If you want to have all the module dependency configurations in one file, you can format it like this:

var config = {
    'profileA': [ 'module1' ],
    'profileB': [ 'module2' ]
};
var currentProfile = 'profileA';
angular.module('app', config[currentProfile]);

      

Since it is set up before the angular application is defined (and thus loaded), angular doesn't care where your module dependencies come from. As long as the .js files of the real modules are loaded. However, you will not be able to change your profile without refreshing your browser.

+1


source







All Articles