7

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': $locale.id.slice(0, 2)
})
scniro
  • 16,844
  • 8
  • 62
  • 106
ciembor
  • 7,189
  • 13
  • 59
  • 100

2 Answers2

8

this is not possible for two reasons.

  1. constant can not have dependencies (see table bottom https://docs.angularjs.org/guide/providers)

  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

angular.module('app')
  .factory('LOCALE_ID', function($locale) {
      return {'LOCALE': $locale.id.slice(0, 2)}
  })
milanlempera
  • 2,203
  • 1
  • 17
  • 21
6

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

scniro
  • 16,844
  • 8
  • 62
  • 106
  • I am not sure if is good ideal call angular.injector inside module code. Typical using is cooperation with third part libraries. I think this is angular services live cycle workaround – milanlempera Jul 15 '15 at 15:39
  • Seems fine to me. Can you give some definitive reason as to why this would not be a good idea? Don't agree with the downvote, OP is satisfied with the answer – scniro Jul 15 '15 at 16:01
  • Question is "How to inject service to angular constant" and general, answer is nowise. In special use case (here inject service from ng module) is it possible but, i think your solutions goes against the purpose of DI. DI says show your dependencies and here you are loading value from global dependency. (docs says inject is for "access to the injector from outside Angular" ) Moreover angular constants (by definition) can not have dependencies. They are formed in a different step of lifecycle (see my post and documentation link). Therefore, I think that your answer is not good. – milanlempera Jul 15 '15 at 20:11
  • 2
    `angular.injector` states - ["Creates an injector object that can be used for retrieving services as well as for dependency injection"](https://docs.angularjs.org/api/ng/function/angular.injector). We are retrieving the `$locale` service. This is totally valid. – scniro Jul 15 '15 at 22:35