Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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': $locale.id.slice(0, 2)
})
like image 969
ciembor Avatar asked Jul 15 '15 13:07

ciembor


2 Answers

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)}
  })
like image 65
milanlempera Avatar answered Oct 03 '22 15:10

milanlempera


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

like image 24
scniro Avatar answered Oct 03 '22 14:10

scniro