Wednesday, March 20, 2013

Constants in AngularJs

Angular has a compile process.  Functions might not be ready when directives need them.  Constants are compiled and evaluated earlier than directives.  The constants defined in mySettings is ready for use by directives when called.
Using constants also helps keep some order in the app. I'm using the same names or interface for the constants on each page.  Some constants such as apiUri are referenced five or six times on each page.  Each page has different values, but the interface is the same.  I prefer constants over hard coding strings.

The directive shown below is not my service, don't let the name fool you.  I use it to call an xml file.  Then directives with lower priorities generate behavioral aspects for the page.  My app is more document centric than model centric.  The MVC is very light. 

//root module

var myApp = angular.module('CoiApp',[]);
//constants
myApp.constant('mySettings', {
    apiUri: '/api/foo',
    nsUri: 'mySite/foo.xsd',
    nsPrefix: 's'
});

//directive using constants, mySettings is injected in using the minification safe method.
mayApp.directive('getById',
    ['$log', '$location', 'mySettings'
        function ($log, $location, mySettings) {
            return {
                priority: 500,
                templateUrl: mySettings.apiUri +'/' +  ($location.search()).myid
            };
}]);

13 comments:

  1. Awesome primer. We are using this pretty extensively as part of our open web stack. Fun!

    ReplyDelete
    Replies
    1. Can you send me a url, I'd love to check it out.

      Delete
    2. https://github.com/OpenWebStack

      Delete
  2. Thank you Dear! It was really useful.

    ReplyDelete
  3. Thanks. At least if this was fucking documented properly.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Thanks for this little nugget that helped me very much.

    ReplyDelete
  6. How can i access the constant in template.html

    ReplyDelete
    Replies
    1. sure,
      [...].controller('myController', ['$scope', 'mySettings' function ($scope, mySettings) {
      $scope.mySettings = mySettings;
      })

      then in your template you can just use {{mySettings.priority}}

      Delete
  7. It might helpful for "How to create and inject the constants in AngularJs?"
    http://www.code-sample.com/2015/06/angularjs-constants.html

    ReplyDelete