REQUEST A DEMO

Organizing your Angular App with Constants

Often times we find ourselves coding strings into our javascript that when seriously thought through, should have been constants. One good example I found in my own code was a factory that sends statistics down to our server. The factory was coded to take in a topic along with the action performed. This is all good, the issue was in the controllers sending the data into the factory. I found I was sending hard coded strings which didn’t sit well with me. An example of this would look like:

$scope.linkClickedStat = function(linkLocation) {
    statFactory.sendStat('LinkClicked', linkLocation);
}

The first part of the signature as you can see I am sending a hard coded string of LinkClicked. How can this be a problem later? Well, a couple of issues here.

  1. I could misspell this in another controller and our stats will be off
  2. The stat topic itself could be changed on the server, I would have to update all controllers on the client

How can this be solved? Since we are using AngularJS, we have the ability to create a constant off our module. So for simplicity, lets go off our main module.

angular.module('MainApp', []).constant('appConstants', {
    topic: {
        linkClicked: 'LinkClicked',
        anotherTopic: 'SomethingElse'
    },
    otherConstant: 'OTHER'
});

Now that I have defined some constants, I can access these inside any module within our application. Because angular has DI, we simply take in a dependency on our appConstants. Assume the linkClickedStat code above was inside a controller called LinkController.

angular.module('MainApp')
    .controller('LinkController', ['$scope', 'appConstants', 'statFactory', function($scope, appConstants, statFactory) {

    $scope.linkClickedStat = function(linkLocation) {
        statFactory.sendStat(appConstants.topic.linkClicked, linkLocation);
    }
}]);

Conclusion

So what did this buy us? I now have one location for my constants. I have removed the chances of a typo and if topics change I have one location to make the change. Other strings such as route urls or messages could be stored here as well. I hope this helps you and as always, Happy Coding.

%d bloggers like this: