fbpx Skip to content

Aquent | DEV6

Using Constants in AngularJS

Written by: Rod Nolan

Use constants in AngularJS to make your code easier to read, understand and maintain

You may find yourself having to work with values (ex. data returned from an API)that are difficult to understand. Consider this example:

console.log(data.customerType);
// 'hvr'

You may have to make decisions in your application based on that data. It can be easy to find yourself in this situation.

switch (data.customerType) {
  case: 'hvr'
    // hmmm... what does 'hvr' mean?
   
  case: 'otp' 
    // wait... what?!
  
  case: 'xyz'
    //  I better ask someone from the back end team what
    //all of these acronyms mean 
   
    // fill in any number of case statements
    // using equally cryptic values here
  
}
switch (data.customerType) {
  case: 'hvr'
    // high value repeat
   
  case: 'otp' 
    // one-time purchase
   
  case: 'xyz'
    //  I think you get the point by now
   
}

When you track down the right team member and get the answers you need to solve the immediate problem, you can just implement your solution and leave it at that. If you think ahead and realize that you (or some other developer who arrives on the scene later) might need this information again, you might sprinkle your code with comments explaining the meaning of those cryptic values.

But you don’t have to stop there. If this data makes multiple appearances in a bunch of different places in your application, I would argue that you should NOT stop there. You can make two small changes to make the lives of your team mates, present and future, a whole lot easier.

You can define some constants.

The names of the constants will reflect the meaning of the values they represent. They are self documenting. And you’ll never have to use the actual values in your code so it’ll be easier to avoid bugs related to typographical errors.

OK, you’re convinced that it’s a good idea. Implementing constants involves two simple steps:

  1. Define the constants in your module
  2. Inject and use them in your controller(s).

Defining constants in an AngularJS application

Use the “$provide” service in the module’s “config” function.

var app = angular.module('UseConstantsToMakeYourCodeUnderstandable', [])
  .config(function ($provide){
    $provide.constant('customerTypes', {
      HIGH_VALUE_REPEAT: 'hvr',
      ONE_TIME_PURCHASE: 'otp',
      ANOTHER_MEANINGFUL_NAME: 'acv' //another cryptic value
    });
  });

Now you have a variable called “customerTypes” that can be injected anywhere you need to use it.

Injecting and using constants in an Angular controller

app.controller('MainCtrl', function($scope, customer, customerTypes) {
  
  $scope.calculateDiscount = function() {
    let discountPercentage = 0;
    switch (customer.customerType) {
  
      case: customerTypes.HIGH_VALUE_REPEAT
        discountPercentage = 15;
       
  
      case: customerTypes.ONE_TIME_PURCHASE
        discountPercentage = 5;
       
  
      case: customerTypes.ANOTHER_MEANINGFUL_NAME
        discountPercentage = 25;
    
    return discountPercentage;
  }
  
});

Visit this plunker https://embed.plnkr.co/pZUh4YpvrgjOH3iEZH8Q if you’d like to experiment with this technique. 

Want to learn more Angular?

Sign up for Angular training course

View Course Details