Christian BouvierDec 22, 2016

Constants in AngularJS

We all know from Programming 101 that a value that remains unaltered during a program execution, is a Constant, and never, but NEVER should we use variables o simply values to represent something with this particular attribute.

The use of constants is more or less trivial, depending on the programming language you are using, and the advantages of using it are many:

  • Elegance
  • Order
  • Readability
  • Semantics
  • Parametrization

and so on..

The goal of this post is to show you a simple way of dealing with Constants in the opinionated AngularJS’s structure. A method that we use in Octobot sometimes.

As always, we try to keep it as simple as posible, in a way which we could manipulate it quickly, easily and without confusion. The result of this is an AngularJS module called CONST, which has all the constants your app needs as attributes.

// ------------------------------------------------------------------------------
// *** Constants ***
// ------------------------------------------------------------------------------

"use strict";

angular.module('yourAngularApp')

.constant('CONST', {
 CONSTANT1 : 'value1',
 CONSTANT2 : 'value2',
 CONSTANT3 : 'anotherStringValue',

 CONSTANT4: 4,
 CONSTANT5: 5.0,
});

Then, any other AngularJS component (controllers, services, factories, etc..) could inject the CONST module and use its values, as follows:

'use strict';

/**
 * @ngdoc function
 * @name yourAngularApp.controller:ExampleCtrl
 * @description Example controller for
 */
angular.module('yourAngularApp')
  .controller('ExampleCtrl',['CONST',  function (CONST) {

  	var controller = this;

  	controller.something = CONST.CONSTANT1; // value1
  	...

  }]);

That’s it!

Note: We are using a very similar concept to deal with variables or constants that are environment-dependent, but we’ll talk about that in a future post.