AngularJS-Shield-large

Our favourite way to structure AngularJS project

By James Martin, published Monday, January 26th, 2015


I touched on this in my previous blog post, but I thought it might be worth while explaining a few of the common ways to structure AngularJS applications, and the explain why we like the one we do.

Simple

If you’re coming from, say, a PHP background, you may decide to organise your files by their type – directives go into the directives folder, controllers into the controllers folder, etc.

Whilst this might seem like the easiest way to begin with, and indeed is perfectly fine for smaller applications, if your application becomes larger, you’ll soon find that it’s taking a lot longer for you to find the file you want.

And the problem is even more obvious with the tests folder – everything you write (theoretically) should be tested, which means your test folder can very quickly get enormous, and not to mention hard to navigate.

Organised by concept

A better way (and frequently recommended by the community) to organise your files is by concept. This can be a bit open to interpretation, but essentially you need to break your application down into small chunks of functionality – for some programs, you can use pages.

For example, if you have a page that shows report, you can make a reports folder in your application directory, and inside it, then organise by type.

So the structure would look something like this:

app
|___reports
    |___directives
    |___controllers
    |___services
    |___tests

Variations

This is just about the best way to organise your files in Angular, but there are a few variations on this that may work better for you:

Tests in with components

Having a dedicated tests folder can become huge when you’ve got dozens of components.

To make it easier for you to find the test you’re looking for, you can put the test in with the Javascript it’s testing. This is often suffixed with *-spec.js, i.e. component-spec.js. If you use Karma for tests, you can make it find all files that end with -spec.js for testing automatically.

Break concepts into modules

Instead of simply splitting your ‘concepts’ into folder, you can go one step further and split them off into separate modules entirely.

Your modules can even have child modules, so you can infinitely nest as you see appropriate. For organisations sake, it makes sense though to only include a module on its parent, don’t include nested modules straight onto the app definition. Whilst this might seem inconvenient, the way Angular loads modules actually means it changes very little – you can still access services and filters, etc, created on another, unrelated module.

Creating modular code like this is great for new feature rollouts, as you can have all code present in your structure and disable/enable is simply by changing one line. It keeps concerns very nicely seperated.