A jumbled mess
If you’ve ever developed a large Angular JS app, you’d agree with me that one of the few problems you will come to face with is Organisation. Its actually very common to group all controllers, directives, factories, and services into one file respectively. However, you soon realise the error in your ways as the application starts getting larger & larger.
This article would show you how we have managed to keep everything neat and tidy as we work through clients jobs. This doesn’t mean this is the best way, it just is a clean way. You are free to come up with yours, no strict policies.
Although this tutorial can be applied to any Angular JS app, I’ll be using Zurb Foundation for Apps as a casing point in this article as it’s built with Angular JS.
Separating concerns
Since the problem remains that as we develop, controllers, factories etc tend to start piling up, thus making it harder to find stuff, we want to separate all the controllers into modules. One of the beauties of Angular is the modularity, so lets take advantage of that in our applications.
Now, after you have installed Zurb Foundation, you’ll have a assets/js directory for everything JS. Thats fine. Now instead if creating our controllers.js, directives.js etc files in this folder directly, we want to create modules and then drop related controllers et al. there.
What qualifies as a module?
Well, thats left for you to decide. However, we like to create a module per “page”. Meaning, for us if the application has 3 pages: Home, About, Contact; we will create three modules respectively. Finally we create another module called the SharedModule. This will contain all our shared dependencies.
After everything has been created modularly, we add each module created as a dependency to our app.js file. Finally, in our gulpfile we can instruct the module directory files to be combined into a single app.js file.
Conclusion
This tutorial was confusing, I know. So, like every good developer, you can learn from the source code. I have included a simple starter application and its available on Github. You can see from the application how everything is tied together.
While the advantages may not be clear now, you’ll see on the long run that separating your Angular logic into controllers is actually better for you.