The two most simple formulas are Constant and Value.

A  Constant is simply a special form of Value that Angular will not allow you to change after instantiation.

As such, the two follow a very similar formula. Assuming your have some module defined elsewhere, you can add constants and values using the following syntax:

Defining a Constant
angular
.module('moduleName')
.constant('NameOfConstant', 'constantValue')
.value('NameOfValue', 'changableValue');

To reuse this constant in other providers / controllers of your app, you could then inject it like so:

Reusing a Constant In a Controller
angular
.module('moduleName', [])
.controller('NameOfController', [ '$scope', 'NameOfConstant', 'NameOfValue', function($scope, nameOfConstant, nameOfValue) {
  // evaluating nameOfConstant should yield our 'constantValue'
  console.log(nameOfConstant);
 
  // evaluating nameOfValue should yield our 'changableValue'
  console.log(nameOfValue);
}]);
Reusing a Constant In Another Provider
angular
.module('moduleName', [])
.service('NameOfService', [ 'NameOfConstant', 'NameOfValue', function(nameOfConstant, nameOfValue) {
  // evaluating nameOfConstant should yield our 'constantValue'
  console.log(nameOfConstant);


  // evaluating nameOfValue should yield our 'changableValue'
  console.log(nameOfValue);
}]);
  • No labels