angularjs 国际化_AngularJS应用程序的国际化

angularjs 国际化

There is a time for each project when internationalization becomes absolutely needed. Sometimes it's because of regional specific customers or when the application has to be shown to people in many countries. Usually, when its architecture is not ready for that- it starts becoming a really painful process.

每个项目都有一段时间绝对需要国际化。 有时是因为特定地区的客户,或者是在许多国家/地区向人们展示该应用程序的时候。 通常,当其架构尚未准备就绪时,它将开始成为一个非常痛苦的过程。

In the AngularJS world, there's the awesome angular-translate (it's used for handling language translation stuff) and the angular-dynamic-locale (it's used for changing angular $locale- which means formatting dates, numbers, currencies, etc.) libraries.

在AngularJS世界中,有很棒的angular-translate (用于处理语言翻译内容)和angular-dynamic-locale (用于更改angular $ locale ,这意味着格式化日期,数字,货币等)库。

On the other hand we have the really popular Yeoman AngularJS generator, which is widely used for scaffolding AngularJS applications.

另一方面,我们拥有真正流行的Yeoman AngularJS生成器 ,该生成器广泛用于脚手架AngularJS应用程序。

Let's provide asynchronous translate (without page reload) to Yeoman's AngularJS application.

让我们向Yeoman的AngularJS应用程序提供异步转换(无需重新加载页面)。

Be sure to checkout the demo.

一定要签出演示

i18n-angular-applications

用Yeoman创建AngularJS应用 (Creating an AngularJS App with Yeoman)

In Github, you can find detailed instructions on how to create applications using generator-angular.

Github中 ,您可以找到有关如何使用generator-angular创建应用程序的详细说明。

In our case just run:

在我们的情况下,只需运行:

npm install -g generator-angular

mkdir angular-translate-yeoman && cd $_

yo angular translate

Answer "Yes" to all questions regarding the decision to use Sass and Sass Bootstrap versions. Leave the default list of AngularJS modules:

对有关使用Sass和Sass Bootstrap版本的决定的所有问题回答“是”。 保留AngularJS模块的默认列表:

yeoman-angular-install

After a while you will have the Yeoman-based Angular application with some pre-generated file structure and pre-defined controllers, views, and even some tests.

一段时间后,您将获得基于Yeoman的Angular应用程序, 其中包含一些预生成的文件结构和预定义的控制器,视图,甚至是一些测试。

To run it in you browser with the live-reload, on any changes, just run:

要通过实时重载在浏览器中运行它,请进行以下更改:

grunt serve

It might look similar to that.

它可能类似于那个

添加i18n (Adding i18n)

  1. We have to download libraries and include them in the project.

    我们必须下载库并将其包含在项目中。
  2. Then we'll need to provide translation files and set them working.

    然后,我们需要提供翻译文件并将其设置为工作状态。
  3. Next, we will change angular $locale after the language change.

    接下来,我们将在更改语言后更改角度$ locale。
  4. Once step 4 is complete, we need to have the drop-down with the list of languages to select from.

    完成第4步后,我们需要在下拉菜单中选择要使用的语言。
  5. Lastly, the selected language should be stored and applied after the page reloads.

    最后,页面重新加载后应存储并应用所选语言。

添加Bower依赖项 (Adding Bower Dependencies)

Run in the shell:

在外壳中运行:

### ANGULAR-TRANSLATE STUFF
# adds angular-translate library
bower install --save angular-translate

# util for asynchronous loading translations files
bower install --save angular-translate-loader-static-files
# util to save selected language preferences to localStorage
bower install --save angular-translate-storage-local
# util to track missed IDs in translation files
bower install --save angular-translate-handler-log

# ANGULAR-DYNAMIC-LOCALE STUFF
# adds angular-dynamic-locale library
bower install --save angular-dynamic-locale

# list of predefined settings for each locale
bower install --save angular-i18n

在模板中应用翻译 (Applying translations in the templates)

Let's add a translation for Splendid! text on the green button. We can do it by applying to this text translate filter in app/views/main.html:

让我们为Splendid!添加翻译Splendid! 绿色按钮上的文字。 我们可以通过在app/views/main.htmlapp/views/main.html此文本转换过滤器来做到这一点:

{{"views.main.Splendid!" | translate}}

I also provided a prefix for translations to quickly figure out where they are used:

我还为翻译提供了前缀,以快速弄清它们的使用位置:

views.main.Splendid! -> views folder, file main.html

views.main.Splendid! -> views文件夹,文件main.html

Using this, in this way, you can provide translations for all your templates.

通过这种方式,您可以为所有模板提供翻译。

提供翻译文件 (Providing Translations Files)

Create files app/resources/locale-{{locale}}.json where {{locale}} - needed locales to handle. In the current example I'll provide the following locales:

创建文件app/resources/locale-{{locale}}.json ,其中{{locale}} -需要处理的语言环境。 在当前示例中,我将提供以下语言环境:

app/resources/locale-en_US.json for English (United States):

app/resources/locale-en_US.json于英语(美国)的app/resources/locale-en_US.json

{
    "views.main.Splendid!": "Splendid!",
    "directives.language-select.Language": "Language"
}

app/resources/locale-ru_RU.json for Russian (Russia):

俄语(俄罗斯)的app/resources/locale-ru_RU.json

{
    "views.main.Splendid!": "Отлично!",
    "directives.language-select.Language": "Язык"
}

directives.language-select.Language will be used in languages dropdown.

directives.language-select.Language将在语言下拉列表中使用。

在AngularJS应用程序中包括angular-translate和动态加载 (Including angular-translate and dynamic loading in AngularJS applications)

In appscriptsapp.js file:

appscriptsapp.js文件中:

Add dependencies for the main app:

为主应用程序添加依赖项:

angular.module('translateApp', [
 ...
 'pascalprecht.translate',// angular-translate
 'tmh.dynamicLocale'// angular-dynamic-locale
])

Provide info about locales and the preferred locale which are used in your app (key values will be used in languages dropdown):

提供有关您的应用中使用的语言环境和首选语言环境的信息(键值将在语言下拉列表中使用):

.constant('LOCALES', {
    'locales': {
        'ru_RU': 'Русский',
        'en_US': 'English'
    },
    'preferredLocale': 'en_US'
})

To get warnings in the developer console, regarding forgotten IDs in translations, just add:

要在开发者控制台中获得有关翻译中遗忘的ID的警告,只需添加:

.config(function ($translateProvider) {
    $translateProvider.useMissingTranslationHandlerLog();
})

Next step is about adding asynchronous loading for the translations:

下一步是为翻译添加异步加载:

.config(function ($translateProvider) {
    $translateProvider.useStaticFilesLoader({
        prefix: 'resources/locale-',// path to translations files
        suffix: '.json'// suffix, currently- extension of the translations
    });
    $translateProvider.preferredLanguage('en_US');// is applied on first load
    $translateProvider.useLocalStorage();// saves selected language to localStorage
})

And, finally, provide the config with direction of where to load the $locale settings files for angular-dynamic-locale:

最后,为配置提供方向,以向何处加载$ ange angular-dynamic-locale的$ locale设置文件:

.config(function (tmhDynamicLocaleProvider) {
    tmhDynamicLocaleProvider.localeLocationPattern('bower_components/angular-i18n/angular-locale_{{locale}}.js');
})

AngularJS服务,用于获取/设置当前语言环境 (AngularJS service for getting / setting current locale)

We need to have some Services to change language and apply some additional logic (e.g. change AngularJS $locale). This will be used for creation and interaction with the languages drop down later.

我们需要一些服务来更改语言并应用一些其他逻辑(例如,更改AngularJS $ locale)。 这将用于创建以及以后与语言的交互。

Create app/scripts/services/LocaleService.js file with the following content:

创建具有以下内容的app/scripts/services/LocaleService.js文件:

angular.module('translateApp') .service('LocaleService', function ($translate, LOCALES, $rootScope, tmhDynamicLocale) {
    'use strict';
    // PREPARING LOCALES INFO
    var localesObj = LOCALES.locales;

    // locales and locales display names
    var _LOCALES = Object.keys(localesObj);
    if (!_LOCALES || _LOCALES.length === 0) {
      console.error('There are no _LOCALES provided');
    }
    var _LOCALES_DISPLAY_NAMES = [];
    _LOCALES.forEach(function (locale) {
      _LOCALES_DISPLAY_NAMES.push(localesObj[locale]);
    });

    // STORING CURRENT LOCALE
    var currentLocale = $translate.proposedLanguage();// because of async loading

    // METHODS
    var checkLocaleIsValid = function (locale) {
      return _LOCALES.indexOf(locale) !== -1;
    };

    var setLocale = function (locale) {
      if (!checkLocaleIsValid(locale)) {
        console.error('Locale name "' + locale + '" is invalid');
        return;
      }
      currentLocale = locale;// updating current locale

      // asking angular-translate to load and apply proper translations
      $translate.use(locale);
    };

    // EVENTS
    // on successful applying translations by angular-translate
    $rootScope.$on('$translateChangeSuccess', function (event, data) {
      document.documentElement.setAttribute('lang', data.language);// sets "lang" attribute to html

       // asking angular-dynamic-locale to load and apply proper AngularJS $locale setting
      tmhDynamicLocale.set(data.language.toLowerCase().replace(/_/g, '-'));
    });

    return {
      getLocaleDisplayName: function () {
        return localesObj[currentLocale];
      },
      setLocaleByDisplayName: function (localeDisplayName) {
        setLocale(
          _LOCALES[
            _LOCALES_DISPLAY_NAMES.indexOf(localeDisplayName)// get locale index
            ]
        );
      },
      getLocalesDisplayNames: function () {
        return _LOCALES_DISPLAY_NAMES;
      }
    };
});

语言下拉菜单 (Language Dropdown)

In this part we will add the language drop down and set actions to changing the language in it. This select element has to be shown only when there are more than 1 languages provided.

在这一部分中,我们将添加语言下拉菜单,并设置操作以更改其中的语言。 仅当提供的语言不只一种时,才必须显示此选择元素。

Let's create an AngularJS directive app/scripts/directives/LanguageSelectDirective.js:

让我们创建一个AngularJS指令app/scripts/directives/LanguageSelectDirective.js

angular.module('translateApp') .directive('ngTranslateLanguageSelect', function (LocaleService) { 'use strict';

        return {
            restrict: 'A',
            replace: true,
            template: ''+
            '<div class="language-select" ng-if="visible">'+
                '<label>'+
                    '{{"directives.language-select.Language" | translate}}:'+
                    '<select ng-model="currentLocaleDisplayName"'+
                        'ng-options="localesDisplayName for localesDisplayName in localesDisplayNames"'+
                        'ng-change="changeLanguage(currentLocaleDisplayName)">'+
                    '</select>'+
                '</label>'+
            '</div>'+
            '',
            controller: function ($scope) {
                $scope.currentLocaleDisplayName = LocaleService.getLocaleDisplayName();
                $scope.localesDisplayNames = LocaleService.getLocalesDisplayNames();
                $scope.visible = $scope.localesDisplayNames &&
                $scope.localesDisplayNames.length > 1;

                $scope.changeLanguage = function (locale) {
                    LocaleService.setLocaleByDisplayName(locale);
                };
            }
        };
    });

包括语言环境服务和语言选择 (Including locale service and language select)

And don't forget to include these scripts and language selects in the app/index.html:

并且不要忘记在app/index.html包含这些脚本和语言选择:

...
<div ng-translate-language-select></div>
...

<!-- build:js({.tmp,app}) scripts/scripts.js -->
... 
<script src="scripts/services/LocaleService.js"></script>
<script src="scripts/directives/LanguageSelectDirective.js"></script>
<!-- endbuild -->

更新Grunt配置 (Updating Grunt Config)

The last thing is we have to let Grunt know about our additions.

最后一件事是我们必须让Grunt知道我们的添加项。

For that we will update Gruntfile.js:

为此,我们将更新Gruntfile.js

  • "live-reload" task config- will add live reload on changing of translations.

    “实时重新加载”任务配置-将在更改翻译时添加实时重新加载。
// Watches files for changes and runs tasks based on the changed files
watch: {
    ...
    livereload: {
        ...
        files: [
            ...
            '<%= yeoman.app %>/resources/{,*/}*.json'
        ]
    }
}
  • "copy" task config- to copy resources files and locales settings to the result build.

    “复制”任务配置-将资源文件和语言环境设置复制到结果版本。
// Copies remaining files to places other tasks can use
copy: {
    dist: {
        files: [{
            ...
            src: [
                ...
                'resources/{,*/}*.*'
            ]
        },
        ...
        {
        expand: true,
        cwd: 'bower_components/angular-i18n/',
        src: '*.js',
        dest: '<%= yeoman.dist %>/bower_components/angular-i18n'
        }]
    }
    ...
}

跑步 (Running)

After that you can test the text Splendid! and see that it really is changed after switching language in dropdown. For that just run:

之后,您可以测试文字Splendid! 并看到在下拉菜单中切换语言后,它确实已更改。 为此,只需运行:

grunt serve # will compile and open project in the browser

To test the distribution build just run:

要测试发行版本,只需运行:

grunt # will create distribution version of the application

and then open dist/index.html in your browser.

然后在浏览器中打开dist/index.html

演示版 (Demo)

You can play with working project at Github.

您可以在Github上进行工作项目。

As you can see, until page is loaded, the translations with $locale are not set and an animation is shown. Also, this can be due to the added on language change.

如您所见,在加载页面之前,不会设置带有$ locale的翻译,并显示动画。 同样,这可能是由于增加了语言更改。

On changing the language, you can see that page title, all of the content, and the time format have changed.

更改语言后,您可以看到页面标题,所有内容和时间格式均已更改。

You can compare which parts of the original Yeoman AngularJS project were changed to add localization looking at Github diff between the branches with the clear AngularJs Yeoman app and with the applied asynchronous translation.

您可以比较原始Yeoman AngularJS项目的哪些部分,以使用清晰的AngularJs Yeoman应用程序和应用的异步翻译来查看分支之间的Github diff,从而添加本地化。

技巧和窍门 (Tips and tricks)

In this section we will review some examples of providing language-specific content.

在本节中,我们将回顾一些提供特定于语言的内容的示例。

范本 (Templates)

文本 (Text)

As above, we can apply translations for templates using e.g. translate filter:

如上所述,我们可以使用翻译过滤器为模板应用翻译:

{{"views.main.Splendid!" | translate}}

There are also a couple of other techniques.

还有其他一些技巧

标题和属性 (Title and attributes)

To apply a changing page title and a meta[name="description"] attribute (which is used to provide text for sharing in social networks), you can use angular ng-bind and ng-attr-content directives (see how it's done in the demo app):

要应用更改的页面标题和meta[name="description"]属性(该属性用于提供文本以在社交网络中共享),可以使用有角度的ng-bindng-attr-content指令(查看操作方式)在演示应用中 ):

<title ng-bind="pageTitle">i18n for your AngularJS applications</title>
<meta name="description" ng-attr-content="{{pageContent}}" content="How to translate your AngularJS applications without page reload with angular-translate">

and to provide an update to these fields in controller:

并提供对控制器中这些字段的更新:

$translate(pageTitleTranslationId, pageContentTranslationId)// ON INIT
 .then(function (translatedPageTitle, translatedPageContent) {
  $rootScope.pageTitle = translatedPageTitle;
  $rootScope.pageContent = translatedPageContent;
});

$rootScope.$on('$translateChangeSuccess', function (event, data) {// ON LANGUAGE CHANGED
 $rootScope.pageTitle = $translate.instant(pageTitleTranslationId);
 $rootScope.pageContent = $translate.instant(pageContentTranslationId);
});

图片 (Images)

You can replace your images when you switch the language providing {{locale}} part to ng-src attribute in your views:

在视图中将提供{{locale}}部分的语言切换为ng-src属性时,可以替换图像:

<img ng-src="images/no-filerev/yeoman-{{locale}}.png" />

And in the controller:

并在控制器中:

$scope.locale = $translate.use();// ON INIT

$rootScope.$on('$translateChangeSuccess', function (event, data) {// ON LANGUAGE CHANGED
 $scope.locale = data.language;
});

You, also, can check it out on the Home page (Yeoman image).

您也可以在主页上将其签出(Yeoman图像)。

CSS (CSS)

If you want to apply some specific css, depending on current locale, you can do it, because in our example we provided the lang attribute for the <html/> tag with current locale value. E.g.:

如果要根据当前语言环境应用某些特定CSS,则可以执行此操作,因为在我们的示例中,我们为<html/>标记的lang属性提供了当前语言环境值。 例如:

[lang="ru_RU"]{
    /*some special styles*/
}

You can see that by switching the language on the About page - it will, then, change the page layout.

您可以通过在“ 关于”页面上切换语言来看到它-然后,它将更改页面布局。

结论 (Conclusion)

Step-by-step we have provided localization for our Yeoman AngularJS app.

我们已逐步为Yeoman AngularJS应用提供了本地化。

We understand how to create translations files, handling translations in html-templates, and AngularJs controllers.

我们了解如何创建翻译文件,如何在html模板和AngularJs控制器中处理翻译。

Also, we discussed how to provide specific styles/images/page titles and even some html attribute values for different locales.

此外,我们讨论了如何为不同的语言环境提供特定的样式/图像/页面标题,甚至一些html属性值。

Who knows, maybe it's a good idea for creation a Yeoman "angular-translate" generator :)

谁知道,也许这是创建Yeoman“角度翻译”生成器的好主意:)

Let me know what your experience has been with the localization? Would you like to see some more of the above or some other parts to be highlighted/described in more detail? I want to hear from you!

让我知道您在本地化方面的经验吗? 您是否希望看到上面的其他部分或其他要突出显示/更详细描述的部分? 我想和你联系!

聚苯乙烯 (P.S.)

Some of the code examples in this article are shown in a reduced manner to show the main code and idea.

以简化的方式显示了本文中的一些代码示例,以显示主要代码和思想。

These symbols ... mean that some parts of the code are left out.

这些符号...意味着代码的某些部分被省略了。

All code and working AngularJS applications, with asynchronous languages loading, can be found in Github.

可以在Github中找到所有具有异步语言加载功能的代码和可用的AngularJS应用程序。

翻译自: https://scotch.io/tutorials/internationalization-of-angularjs-applications

angularjs 国际化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值