AngularJS在lang更改时更改语言环境文件

时间:2017-03-14 14:34:11

标签: javascript angularjs

我们有一个angularJS应用程序,支持多种语言。

在我们的主应用模块中,我们定义了:

.config(function ($translateProvider, $translatePartialLoaderProvider) {
    $translateProvider.useLoader("$translatePartialLoader", {
        urlTemplate: "/js/app/i18n/{lang}.json"
    });
    $translateProvider
    .registerAvailableLanguageKeys(['en', 'fr'], {
        'en_US': 'en',
        'en_UK': 'en',
        'en_CA': 'en',
        'fr_FR': 'fr',
        'fr_CA': 'fr',
        'fr_BE': 'fr',
        '*': 'en'
    })
    .fallbackLanguage('en')
    .determinePreferredLanguage();

在我们的主控制器中,我们选择更改lang,调用此函数:

this.changeLang = function () {
        $translate.use(self.currentLang).then(function () {
            // Here we want to trigger the call to another angular i8ln file
        }, function () {
            MessageService.show("error", $translate.instant("lang_change_error"));
        });
    };

但我们希望使用角度i8ln功率来转换某些数据,例如datepickers。

我们知道我们必须在加载角度应用的index.html中加载角度i8ln区域设置文件。这些文件包含例如:

'use strict';
angular.module("ngLocale", [], ["$provide", function ($provide) {
    var PLURAL_CATEGORY = { ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other" };
    function getDecimals(n) {
        n = n + '';
        var i = n.indexOf('.');
        return (i == -1) ? 0 : n.length - i - 1;
    }

    function getVF(n, opt_precision) {
        var v = opt_precision;

        if (undefined === v) {
            v = Math.min(getDecimals(n), 3);
        }

        var base = Math.pow(10, v);
        var f = ((n * base) | 0) % base;
        return { v: v, f: f };
    }

    $provide.value("$locale", {
        "DATETIME_FORMATS": {
            "AMPMS": [
              "AM",
              "PM"
            ],
            "DAY": [
              "Sunday",
              "Monday",
              "Tuesday",
              "Wednesday",
              "Thursday",
              "Friday",
              "Saturday"
            ],
            "ERANAMES": [
              "Before Christ",
              "Anno Domini"
            ],
            "ERAS": [
              "BC",
              "AD"
            ],
            "FIRSTDAYOFWEEK": 6,
            "MONTH": [
              "January",
              "February",
              "March",
              "April",
              "May",
              "June",
              "July",
              "August",
              "September",
              "October",
              "November",
              "December"
            ],
            "SHORTDAY": [
              "Sun",
              "Mon",
              "Tue",
              "Wed",
              "Thu",
              "Fri",
              "Sat"
            ],
            "SHORTMONTH": [
              "Jan",
              "Feb",
              "Mar",
              "Apr",
              "May",
              "Jun",
              "Jul",
              "Aug",
              "Sep",
              "Oct",
              "Nov",
              "Dec"
            ],
            "STANDALONEMONTH": [
              "January",
              "February",
              "March",
              "April",
              "May",
              "June",
              "July",
              "August",
              "September",
              "October",
              "November",
              "December"
            ],
            "WEEKENDRANGE": [
              5,
              6
            ],
            "fullDate": "EEEE, MMMM d, y",
            "longDate": "MMMM d, y",
            "medium": "MMM d, y h:mm:ss a",
            "mediumDate": "MMM d, y",
            "mediumTime": "h:mm:ss a",
            "short": "y-MM-dd h:mm a",
            "shortDate": "y-MM-dd",
            "shortTime": "h:mm a"
        },
        "NUMBER_FORMATS": {
            "CURRENCY_SYM": "$",
            "DECIMAL_SEP": ".",
            "GROUP_SEP": ",",
            "PATTERNS": [
              {
                  "gSize": 3,
                  "lgSize": 3,
                  "maxFrac": 3,
                  "minFrac": 0,
                  "minInt": 1,
                  "negPre": "-",
                  "negSuf": "",
                  "posPre": "",
                  "posSuf": ""
              },
              {
                  "gSize": 3,
                  "lgSize": 3,
                  "maxFrac": 2,
                  "minFrac": 2,
                  "minInt": 1,
                  "negPre": "-\u00a4",
                  "negSuf": "",
                  "posPre": "\u00a4",
                  "posSuf": ""
              }
            ]
        },
        "id": "en",
        "localeID": "en",
        "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; }
    });
}]);

但是如何根据当前加载的lang加载i8ln文件?

我尝试使用<script>技巧或字符串插值更改ng-if src,但禁止使用XSS注入。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

按照Jack A.的建议,您可以轻松使用angular-dynamic-locale模块。此模块允许您使用简单的函数“触发”区域设置文件的包含。

以下是您可以遵循的步骤:

在项目中包含Angular Dynamic Local模块

您只需按照module README上的步骤操作即可。

特别是,不要忘记:

  • 在模块阵列中包含tmhDynamicLocaleProvider模块:在主应用模块文件的模块阵列中包含tmhDynamicLocaleProvider模块: angular.module("yourApp", ["tmh.dynamicLocale", ... ]);

  • 在您的主应用程序模块中更改区域设置位置配置

应该看起来像:

.config(function ($translateProvider, $translatePartialLoaderProvider) {
    $translateProvider.useLoader("$translatePartialLoader", {
        urlTemplate: "/js/app/i18n/{lang}.json"
    });
    $translateProvider
    .registerAvailableLanguageKeys(['en', 'fr'], {
        'en_US': 'en',
        'en_UK': 'en',
        'en_CA': 'en',
        'fr_FR': 'fr',
        'fr_CA': 'fr',
        'fr_BE': 'fr',
        '*': 'en'
    })
    .fallbackLanguage('en')
    .determinePreferredLanguage();

    // Add these lines to configure path 
    // and set the fallback language the same you defined above
    tmhDynamicLocaleProvider.localeLocationPattern('/base/node_modules/angular-i18n/angular-locale_{{locale}}.js');
    tmhDynamicLocaleProvider.defaultLocale('en');
})

您必须更改/base/node_modules/angular-i18n/以获取相应的路径。还要确保遵守文件命名约定,例如在该目录中包含angular-locale_en.js文件。

然后,从您的控制器,只需使用适当的区域设置参数调用tmhDynamicLocale.set()函数。

在您的代码中,它应该如下所示:

this.changeLang = function () {
    $translate.use(self.currentLang).then(function (lang) {
       // This line will trigger the file change
       tmhDynamicLocale.set(lang);
    }, function () {
        MessageService.show("error", $translate.instant("lang_change_error"));
    });
};