Modules

Avoid Naming Collisions

[Style Y020]
  • Use unique naming conventions with separators for sub-modules.

Why?: Unique names help avoid module name collisions. Separators help define modules and their submodule hierarchy. For example app may be your root module while app.dashboard and app.users may be modules that are used as dependencies of app.

Definitions (aka Setters)

[Style Y021]
  • Declare modules without a variable using the setter syntax.

Why?: With 1 component per file, there is rarely a need to introduce a variable for the module.

  /* avoid */
  var app = angular.module('app', [
      'ngAnimate',
      'ngRoute',
      'app.shared',
      'app.dashboard'
  ]);

Instead use the simple setter syntax.

  /* recommended */
  angular
      .module('app', [
          'ngAnimate',
          'ngRoute',
          'app.shared',
          'app.dashboard'
      ]);

Getters

[Style Y022]
  • When using a module, avoid using a variable and instead use chaining with the getter syntax.

Why?: This produces more readable code and avoids variable collisions or leaks.

  /* avoid */
  var app = angular.module('app');
  app.controller('SomeController', SomeController);

  function SomeController() { }
  /* recommended */
  angular
      .module('app')
      .controller('SomeController', SomeController);

  function SomeController() { }

Setting vs Getting

[Style Y023]
  • Only set once and get for all other instances.

Why?: A module should only be created once, then retrieved from that point and after.

- Use `angular.module('app', []);` to set a module.
- Use `angular.module('app');` to get a module.

Named vs Anonymous Functions

[Style Y024]
  • Use named functions instead of passing an anonymous function in as a callback.

Why?: This produces more readable code, is much easier to debug, and reduces the amount of nested callback code.

  /* avoid */
  angular
      .module('app')
      .controller('Dashboard', function() { })
      .factory('logger', function() { });
  /* recommended */

  // dashboard.js
  angular
      .module('app')
      .controller('Dashboard', Dashboard);

  function Dashboard() { }
  // logger.js
  angular
      .module('app')
      .factory('logger', logger);

  function logger() { }