Here is my sample code: en.js
var translationsEN = {
USERNAME: 'Username',
PASSWORD: 'Password',
LOGIN: 'Login',
CANCEL: 'Cancel' };
and my controller:
.config(function ($routeProvider, $translateProvider) {
...
$translateProvider.translations('en_US', translationsEN);
$translateProvider.preferredLanguage('en_US');
...
I'm using the module angular-translate of Pascal Precht. When I updated my files, in the console is the message: "translationsEN is not defined" (in my controller) and the message from my language file: "translationsEN is defined but never used"
How can I defined the variable in my Controller? Do I need to define the variable as a service?
The Angular way to achieve your goal is indeed to use a service or, in the case of a simple and constant variable, a constant service :
myModule.constant(
'myModule.translations.EN',
{
USERNAME: 'Username',
PASSWORD: 'Password',
LOGIN: 'Login',
CANCEL: 'Cancel'
}
);
All you have to do then is to inject it in your configuration method:
myModule.config([
'$routeProvider',
'$translateProvider',
'myModule.translations.EN',
function ($routeProvider, $translateProvider, translationsEN) {
// …
$translateProvider.translations('en_US', translationsEN);
$translateProvider.preferredLanguage('en_US');
}
]);
If, for some reasons, you absolutely need to use a classical variable, for instance because it's also used in a non-Angular script, simply be sure to declare it before your configuration method.
As @Blackhole explained in his answer, the general way to achieve that in angular is to use a provider.
However, in your specific use case of angular-translate , the way to achieve this would be to load your translation files with $translateProvider
:
Rename en.js
to en_US.json
and put it in a folder named, for example, /locales
. Make sure your files are valid json, ie you want to remove var translationsEN =
.
Then configure $translateProvider
like that :
$translateProvider.useStaticFilesLoader({
prefix: '/locales/',
suffix: '.json'
});
This will load all your json translations files, located in the folder /locales
.
That way your translation files will be totally independent of your application logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.