Advice on one page application - How to break the code into smaller files

18 views
Skip to first unread message

Robin Moss

unread,
Jun 26, 2016, 4:09:00 AM6/26/16
to AngularJS
Hi,

I've been playing a bit with AngularJS and decided to use it to build a literal one page application (http://kdm-webforms.com/) and source (https://github.com/LupusUmbrae/KDM).

This site started as quite a small application, replicate the functionality of a couple of forms as a website, but as its gone on the main JavaScript file has just grown, im hoping to pull it apart into modules and services but i could really do with some pointer/advice and what route i should take for it.

To give you the gist of what this site does. There are two types of forms (stored as JSON, and imported/exported as json), each instance is in a tab, there is not cross tab information so they are isolated from each other. There are a number of dialog for for confirmation of interaction and some have small forms in them that then effect the tab that opened them

The issue i have is in deciphering how the different aspects of the code should be encapsulated (Modules, Controllers, Services ect). As i have a single page it seems like i should have a single module, however i believe i should be able to break some of the functionality out of the main module, for instance breaking all the dialog code out and putting it elsewhere would really reduce the size of the JavaScript file. I'm also working in another branch to implement communication with a backend.

I've been struggling to get my head around how to break this code down and any advice would be really appreciated.

Thanks,
Robin


Sander Elias

unread,
Jun 27, 2016, 12:28:52 AM6/27/16
to AngularJS
Hi Robin,

There are many ways to solve your issue. Roughly in NG1 there are 2 ways.  

//main.js script file, defines your module
angular
.module('main', [])
 
.controller(...)

//child.js script file
angular
.module('main') // notice no ,[] that means it just query's for the module
 
.controller(...)

You define 1 module, and then just reuse wherever you need it.

//main.js script file, defines your module
angular
.module('main', ['child'])
 
.controller(...)

//child.js script file
angular
.module('child',[])
 
.controller(...)


Define a new module in every js file. The most important difference is that the loading order of your script files becomes less of an issue in the second case, and it makes a bit more explicit what your dependencies are. 
For more n depth information, read through the styleguide.

Regards
Sander

Robin Moss

unread,
Jul 1, 2016, 4:46:58 PM7/1/16
to AngularJS
Thanks for the advice Sander should give me a way forward
Reply all
Reply to author
Forward
0 new messages