How to inject service to angular constant


I would like to define a constant which use $locale service. Constants are objects, so I can't inject it as parameter as in case of controller. How can I use it?

angular.module('app').constant('SOME_CONSTANT', {
  'LOCALE': $, 2)
Problem courtesy of: ciembor


You can manually grab $locale with the $injector. Observe the following...

app.constant('SOME_CONSTANT', { 
    'LOCALE': angular.injector(['ng']).get('$locale').id.slice(0, 2) 

JSFiddle Example

Solution courtesy of: scniro


this is not possible for two reasons.

  1. constant can not have dependencies (see table bottom

  2. constants and provider are available in .config functions (config phase), but services ($locale) are available only later (in .run function/phase)

Alternatively you can create service-type factory, which can have dependencies and can create object or primitive

  .factory('LOCALE_ID', function($locale) {
      return {'LOCALE': $, 2)}
Discussion courtesy of: milanlempera

This recipe can be found in it's original form on Stack Over Flow.