[英]How can I define a variable in a controller who is from another file?
Here is my sample code: en.js 这是我的示例代码: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. 我正在使用Pascal Precht的angular-translate模块。 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"
当我更新文件时,在控制台中显示的消息是:“ translationsEN未定义”(在我的控制器中),而来自我的语言文件的消息是:“ translationsEN已定义但从未使用”
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 : 实现您的目标的Angular方法确实是使用服务,或者在简单且恒定的变量的情况下,使用恒定的服务 :
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. 就像@Blackhole在他的回答中解释的那样,实现此目标的一般方法是使用提供程序。
However, in your specific use case of angular-translate , the way to achieve this would be to load your translation files with $translateProvider
: 但是, 在您的angular-translate特定用例中 ,实现此目的的方法是使用
$translateProvider
加载翻译文件:
Rename en.js
to en_US.json
and put it in a folder named, for example, /locales
. 将
en.js
重命名为en_US.json
并将其放置在名为/locales
的文件夹中。 Make sure your files are valid json, ie you want to remove var translationsEN =
. 确保您的文件是有效的json,即您要删除
var translationsEN =
。
Then configure $translateProvider
like that : 然后像这样配置
$translateProvider
:
$translateProvider.useStaticFilesLoader({
prefix: '/locales/',
suffix: '.json'
});
This will load all your json translations files, located in the folder /locales
. 这将加载位于
/locales
文件夹中的所有json转换文件。
That way your translation files will be totally independent of your application logic. 这样,您的翻译文件将完全独立于您的应用程序逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.