user3728375
user3728375

Reputation:

How to Modularize AngularJS app(folder structure)?

Assume I am going to start new AngularJs app with 3 modules:

  1. login
  2. payment
  3. enquiry

I want to load payment module with login details similarly for enquiry, how can we achieve this?

I will have 1 login screen which will call server and check for login, after that server will respond with some parameter which I will use in payment and enquiry module.

If I load login module with other 2 modules:

var myModule = angular.module('myApp', ['payment', 'enquiry']);

It will load both modules on login (I am not sure), but i want like this:

var myModule = angular.module('myApp', ['login']);
// i.e for payment:
var myModule = angular.module('payment', ['login']);
// and for enquiry:
var myModule = angular.module('enquiry', ['login']);

Only login should be loaded. I will use login parameters here.

Any suggestions?

Upvotes: 4

Views: 2991

Answers (1)

Rickard Staaf
Rickard Staaf

Reputation: 2740

Firstly, you are not "loading" the modules with that syntax, only making sure that they are initialized in the right order. Loading the modules is done by including them in your index.html page (or by using requirejs or similar, but that will make it a completely different beast).

Assuming you are building a SPA (Single Page Application) you will only have one main module, and that will have to reference all other modules you want to use, directly or indirectly. So if you do it the way you want, you will never be able to access payment or enquiry. So you should do:

in app.js

var myModule = angular.module('myApp', ['payment', 'enquiry']);

in payment.js

var myModule = angular.module('payment', ['login']);

in enquiry.js

var myModule = angular.module('enquiry', ['login']);

in login.js

var myModule = angular.module('login', []);

in index.html

<html ng-app="myApp">
...
<script src="app.js"></script>
<script src="payment.js"></script>
<script src="enquiry.js"></script>
<script src="login.js"></script>
...
</html>

And remember since you will be including the JavaScript code for all these in the index.html you will "load" all the code always no matter how you define your modules, you will also only have one module "bound" to your application, and that module will have to have access to all other modules you are including.

If you however want to do lazy loading (load resources (modules, controllers, filters, providers etc.) when you need them that is a completely different beast and will require a lot of extra code all over your applications as well as some hackish ways of using angularjs, unless you use something, http://marcoslin.github.io/angularAMD/#/home. There is also a good discussion on if you should or should not use lazy loading here: Does it make sense to use Require.js with Angular.js?

Upvotes: 4

Related Questions