AngularJS StyleGuide

Modules

  • Definitions: Declare modules without a variable using the setter and getter syntax

    // avoid
    var app = angular.module('app', []);
    app.controller();
    app.factory();
    
    // recommended
    angular
      .module('app', [])
      .controller()
      .factory();
    
  • Note: Using angular.module('app', []); sets a module, whereas angular.module('app'); gets the module. Only set once and get for all other instances.

  • Methods: Pass functions into module methods rather than assign as a callback

    // avoid
    angular
      .module('app', [])
      .controller('MainCtrl', function MainCtrl () {
    
      })
      .service('SomeService', function SomeService () {
    
      });
    
    // recommended
    function MainCtrl () {
    
    }
    function SomeService () {
    
    }
    angular
      .module('app', [])
      .controller('MainCtrl', MainCtrl)
      .service('SomeService', SomeService);
    
  • This aids with readability and reduces the volume of code "wrapped" inside the Angular framework

  • IIFE scoping: To avoid polluting the global scope with our function declarations that get passed into Angular, ensure build tasks wrap the concatenated files inside an IIFE

    (function () {
    
      angular
        .module('app', []);
    
      // MainCtrl.js
      function MainCtrl () {
    
      }
    
      angular
        .module('app')
        .controller('MainCtrl', MainCtrl);
    
      // SomeService.js
      function SomeService () {
    
      }
    
      angular
        .module('app')
        .service('SomeService', SomeService);
    
      // ...
    
    })();