JavaScript
Article
By Francesco Iovine

An Introduction to AngularJS Style Guides

By Francesco Iovine

This article was peer reviewed by Tom Greco, Divy Tolia and Rabi Kiran. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

What is a style guide? Do AngularJS projects need a style guide, and why? Which are the most popular AngularJS style guides? How would you use a style guide in a team of developers? This article is going to answer all these questions. Before diving into AngularJS style guides, let’s look at what a style guide is and why we developers need one.

Why Style Guides

Wikipedia provides a good general definition that can be useful to understand why style guides are important and to get the big picture before diving into AngularJS style guides.

A style guide (or manual of style) is a set of standards for the writing and design of documents, either for general use or for a specific publication, organization, or field. A style guide establishes and enforces style to improve communication. To do that, it ensures consistency within a document and across multiple documents and enforces best practice in usage and in language composition, visual composition, orthography and typography. For academic and technical documents, a guide may also enforce the best practice in ethics (such as authorship, research ethics, and disclosure), pedagogy (such as exposition and clarity), and compliance (technical and regulatory).

Coding style guides enforce the best practice in relation to a particular language and to your organization’s needs.

Project Style Guides

There are a number of reasons why JavaScript projects need a style guide. I’m not going to cover all of them in full detail in this article, but they usually expand on the language style guide by covering the following additional topics:

  1. Modularity: single responsibility, immediately invoked function expressions, module dependencies
  2. Application structure: architectural patters, folders structure
  3. Naming conventions: for modules, controllers, configuration and spec files
  4. Linting: JavaScript code checkers
  5. Testing: the approach in writing specs
  6. Comments: to produce documentation
  7. Startup logic: configuration, startup logic
  8. Routing: navigation flow, view composition
  9. Exception Handling: decorators, exception catchers, route errors
  10. Performance and Security: minification, obfuscation

Existing JavaScript Style Guides

For JavaScript there are a number of general and project-specific style guides out there:

Despite the big names, none of the style guides mentioned above is totally comprehensive. In my opinion, the Airbnb style guide is the most up-to-date and complete, and provides also eslint configuration files with which you can automatically check your code style. The eslint configuration files can be extended, as I did when building my web site.

Why AngularJS Projects Need a Style Guide

AngularJS projects need a style guide pretty much for the same reason all JavaScript projects need a style guide, but there are some Angular-specific items that can be covered.

Let’s consider the following AngularJS-specific examples:

  • How to use ng tags. AngularJS ng directives can be used in different ways and have a different syntax, for example preferring data-ng instead of ng when using the ng directive as an HTML attribute, in order to be W3C-compliant. Specifying how to write ng directives in a code style guide helps improving consistency in the HTML files.

  • Different ways to implement components. AngularJS implements web components using custom directives. Custom directives can be based on HTML element names, attributes, class names, as well as comments. A style guide might assure that only one type of directive is used within a project for example.

  • Which architectural pattern to adopt. AngularJS allows for MV* (or MVW) architectural patterns. That leaves the choice to JavaScript developers about whether to implement their application based on MVC or MVVM. Guidelines about what kind of approach has to be used in the project helps in keeping the whole team on the same track.

Now that we have an idea of what Style Guides are for, we are ready to dive in to existing AngularJS Style Guides.

AngularJS Style Guides

Google provides an official style guide and best practices, but the most popular and comprehensive guides are from the AngularJS community :

It’s hard to say which is the best as they are all good style guides. John Papa’s guide is comprehensive and evolving, Todd Motto’s is concise and great to start, and Minko Gechev’s is translated in different languages. But it seems that John Papa’s styleguide has been officially recommended as the most current and detailed AngularJS Style Guide.

These are in my opinion the most important AngularJS-specific points in the Jonh Papa’s style guide to take into consideration when starting a brand new AngularJS projects:

  • The LIFT Principle
  • The controllerAs syntax
  • Fle templates and snippets
  • Seed applications

The LIFT Principle

The LIFT Principle is related to the app structure, and defined the following guidelines:

  1. Locate your code quickly
  2. Identify the code at a glance
  3. keep the Flattest structure you can
  4. Try to stay DRY

This makes the app structure more scalable and developers more efficient because they find code more quickly. Using a folders-by-feature structure naturally helps to follow the principle.

ControllerAs

Using the controllerAs syntax over the ‘classic controller with $scope‘ syntax makes code more readable in the view:

<!-- avoid -->
<div ng-controller="CustomerController">
    {{ name }}
</div>

<!-- recommended -->
<div ng-controller="CustomerController as customer">
    {{ customer.name }}
</div>

and in the controller:

/* avoid */
function CustomerController($scope) {
    $scope.name = {};
    $scope.sendMessage = function() { };
}

/* better */
function CustomerController() {
    this.name = {};
    this.sendMessage = function() { };
}

It’s actually recommended, to go a step further and assign this to a variable, so you can easily access it from within your controller methods:

/* recommended */
function CustomerController() {
    var customerVM = this;
    customerVM.name = {};
    customerVM.sendMessage = function() {
        // we can access the controller's scope as customerVM
    };
}

File Templates and Snippets

In John Papa’s guide, a number of file templates and snippets are listed for different editors and IDEs. Using file templates and snippets ensure consistency among different files, modules, and subsystems, and, especially if you work in a team, this can save a lot of time during a refactoring or when new developers join your team. It also keeps the project’s code clean and reusable.

Seed Applications

If you are in a hurry, or want to learn from a complete example, HotTowel is an option to consider when starting new AngularJS projects. This Yeoman generator creates an app that serves as a starting point for your AngularJS application, following John Papa’s style guide. The generated application is configured with an npm package, a gulp file, JavaScript and LESS hints, so, if you don’t have particular needs, all you have to do is implementing new features! You can browse and run an AngularJS application generated using HotTowel in my AngularJS playground on GitHub.

A Real-World Example

An example of style guide used for a real-world project is the GoCardless AngularJS Styleguide, in which you can find more specific and advanced code snippets. It pushes the usage of directives instead of controllers in the HTML. As an example have a look at this guideline about directive names:

Directive names must only contain a-z and at least one dash (-). Why: Custom elements must have a dash (namespace) to differentiate them from native elements and prevent future component collisions.

<!-- Recommended -->
<dialog-box></dialog-box>
<button click-toggle="isActive"></button>

<!-- Avoid -->
<dialog></dialog>
<button toggle="isActive"></button>

The GoCardless style guide can be a great starting point to get inspired to customize and extend the generic style guides mentioned above based on your team and project needs.

Using a Style Guide in a Team

Code style guides should be a required input for most of the AngularJS projects, especially if the project is expecting to grow fast or the team is new. Also, code style guides should be kept alive during a project, and changed or extended every time a new need or discovery comes up.

The Future: 2016 and Beyond

In the near future, things are going to change fast. The next challenge is updating style guides for AngularJS 2, especially regarding developments with web components, ECMAScript 2015 (ES6), and ECMAScript 2016 and beyond.

I’d love to hear about other people’s experiences with style guides, either for Angular, or JavaScript in general. Are there any great guides that I missed out, or any guidelines that you think are particularly controversial? Let me know in the comments!

  • mbokil

    Nice article. I had seen the newer controller as syntax but avoided. I can see from your example it helps with code readability and organization. Dropping $scope pollution in the controller is also very nice and clean too.

  • Ravi Dasari

    Great article. I have copied all good parts(which I liked most) from goggle and jQuery style guides and made a composite one. But you have have given references to many popular style guide(new to me) which I will consider for my next projects.

    • choose one which you “think you like most”, then improve it or switch another one later

  • Joel Rdz

    Nice article!

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.