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)
})
this is not possible for two reasons.
constant can not have dependencies (see table bottom https://docs.angularjs.org/guide/providers)
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)}
})
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With