Angular.js: Is .value() the proper way to set app wide constant and how to retrieve it in a controller

Module.value(key, value) is used to inject an editable value,
Module.constant(key, value) is used to inject a constant value

The difference between the two isn’t so much that you “can’t edit a constant”, it’s more that you can’t intercept a constant with $provide and inject something else.

// define a value
app.value('myThing', 'weee');

// define a constant
app.constant('myConst', 'blah');

// use it in a service
app.factory('myService', ['myThing', 'myConst', function(myThing, myConst){
   return {
       whatsMyThing: function() { 
          return myThing; //weee
       },
       getMyConst: function () {
          return myConst; //blah
       }
   };
}]);

// use it in a controller
app.controller('someController', ['$scope', 'myThing', 'myConst', 
    function($scope, myThing, myConst) {
        $scope.foo = myThing; //weee
        $scope.bar = myConst; //blah
    });

Leave a Comment