I did it all wrong in my first angularJS application. Oh I did it really wrong!
The structure of my first angular project looked something like this:
- Root folder
So, all controllers were going to “controllers” folder, services into “services” folder and partials lived directly next to full html files. When we started to have more than 10 directives and 5 services the problems with this approach were really backfiring:
- it was not easily visible what files were depending on what other files
- refactorings were thus quite hard
- reusing features in other code/applications was hard as the structure didn’t allow to group files of a single feature together
- it was hard for new developers to understand the flow of the application
- it was hard to extend the application so that it not only consisted of one (single page) application but of two applications that shared some features
Since then I tried a few different approaches and while experimenting with ngStart as a skeleton for new angular projects I’m now settled with an approach I want to use in all my next projects.
What I came up with, is an approach that groups features into angularJS modules. The main advantages is that the code structure is based on features of the application and every feature is defining its own angularJS module. The angular root module then is the glue and binds all modules together.
The structure of ngStart looks like this:
- Root folder
Each angular module can use the full list of angular features. It can have its own angular.config() phase function, can declare its own routes and can have its own list of dependencies.
To refactor a certain feature you now know exactly where to begin and what files are directly dependent on each other when they implement a single feature. You can move modules around and even move them out of the your first single-page app, make another app and declare a dependency on the module to reuse your code.
In a small and trivial example the advantages of this approach are not easily visible, but as soon as a team of developers works together on an application it will grow very fast.
But as frontend engineers or frontend developers of today, you should care! AngularJS is great. But angularJS applications will face the same problems as every other application that begins to grow. And your structure should make it easy to grow and adapt. You should care from the beginning!