We spend a lot of time writing code.
In the early phases of a project, the directory structure doesn’t matter too much and many people tend to ignore best practices. In the short term, this allows the developer to code rapidly, but in the long term will affect code maintainability.
AngularJS is still relatively new and developers are still figuring out what works and doesn’t. There are many great ways to structure an app and we’ll borrow some principles from existing mature frameworks but also do some things that are specific to Angular.
In this article, I will cover best practices regarding directory structures for both small and large AngularJS apps. This may be a hot button issue with some developers and while there is no “perfect” way to structure an app, I will be writing from experience and lessons learned from projects I’ve worked on.
First of all, let’s go over what not to do. Many AngularJS tutorials show an app structure that resembles the code below:
This is a very typical app structure that I see. On the surface, it seems to make a lot of sense and is very similar to a lot of MVC frameworks. We have a separation of concerns, controllers have their own folder,views have their own folder, external libraries have their own folder, etc.
The main problem with this directory structure is not apparent when you are working with only a handful of views and controllers. In fact, it is preferable to follow this approach when writing a tutorial for example or for smaller application. This structure makes it very easy for the reader to visualize and conceptualize the concepts you are covering.
This approach falls apart, however, when you start adding additional functionality to the app. Once you have more than 10 controllers, views and directives, you are going to have to do a lot of scrolling in your directory tree to find the required files.
For example, say you are building a blog with Angular. You decide that you would like to add the author information to the bottom of each article. Well now, you have to find the blog directive, controller, potentially the service and finally the view before you can even look at the whole picture and start making edits.
Say a few months down the line, you are adding additional features to your blog and want to rename a particular feature, again it’s a hunt throughout the directory structure to find the affected files, edit them, make sure they are all in sync, and then make the changes.