Angular 翻译多个 json 文件

Angular translate multiple json files

我正在使用 Angular Cordova 和 Ionic 开发移动应用程序。 我想在我的应用程序中使用多个翻译文件。 喜欢:

我正在使用此代码:

$translateProvider.useStaticFilesLoader({
        prefix: 'main/i18n/local-',
        suffix: '.json'
    });

我的问题是如何加载多个文件?我搜索了很多,但我一无所获。

提前致谢

您可以使用部分加载器: https://github.com/angular-translate/bower-angular-translate-loader-partial

请参阅 How to best organize translation strings in angular-translate? 示例代码

您可能还会发现 angular-translate-loader-pluggable 包很有用, 部分加载器仍然取代加载器提供者,而不是允许任何给定模块的多个加载器。

然后可插拔加载程序成为一种合并的翻译提供程序。它将合并所有已配置加载器的结果。

我使用可插入加载程序允许每个模块的语言文件,以及数据库驱动源。

The idea is that over time, most static string translations will be published into files, however some the user can configure directly at runtime, hence the dbStringProvider. In this example you can see examples of using the factory or provider method for defining the translate function

var module = angular.module('app', [
        'pascalprecht.translate',
        'LocalStorageModule',
        'angular-translate-loader-pluggable'
    ]);

module.provider('$dbStringProvider', $dbStringProvider);
function $dbStringProvider() {
    function isStringValid(str) {
        return angular.isString(str) && str !== '';
    }
    this.$get = ['$rootScope', '$injector', '$q', '$http',
        function ($rootScope, $injector, $q, $http) {
            var service = function (options) {
                // options.key is the requested language identifier
                if (!isStringValid(options.key)) {
                    throw new TypeError('Unable to load data, a key is not a non-empty string.');
                }
                var errorHandler = options.loadFailureHandler;
                if (errorHandler !== undefined) {
                    if (!angular.isString(errorHandler)) {
                        throw new Error('Unable to load data, a loadFailureHandler is not a string.');
                    } else {
                        errorHandler = $injector.get(errorHandler);
                    }
                }
                var deferred = $q.defer(), translations;
                translations = {
                    'TEXT': 'TEST Provider',
                    'TEXT1': 'This is a test (1: Provider)'
                };
                deferred.resolve(translations);
                return deferred.promise;
            };
            return service;
        }];
}

module.factory('dbStringFactory', ['$q', '$http',
    function ($q, $http) {
        var loader = function (options) {
            var deferred = $q.defer();
            var translations = {};
            if (options.key == "en") {
                // Normally we call the database to get the strings
                // The following demonstrates how multiple concurrent providers will provide translations
                translations = {
                    'TEXT': 'TEST Factory',
                    'TEXT2': 'This is a test (2: factory)'
                };
            }
            deferred.resolve(translations);
            return deferred.promise;
        };
        return loader;
    }]);

module.config(translateConfig);

/* @ngInject */
function translateConfig($translateProvider, $translatePartialLoaderProvider, triSettingsProvider, translatePluggableLoaderProvider) {
    
    /**
     * $translateProvider only allows a single loader at a time
     * Use pluggable loader to add and remove loaders whenever you
     * feel the need to, meaning some modules can use entirely different
     * translation loaders without having to destroy any previous configuration
     */
    $translateProvider.useLoader('translatePluggableLoader');

    /**
     *  each module loads its own translation file - making it easier to create translations
     *  also translations are not loaded when they aren't needed
     *  each module will have a i18n folder that will contain its translations
     * So still use partial loader as a loader for the pluggable loader.
     */
    translatePluggableLoaderProvider.useLoader('$translatePartialLoader', {
        urlTemplate: '{part}/i18n/{lang}.json'
    });
    $translatePartialLoaderProvider.addPart('app');

    /**
     *  Pluggable allows us to register multiple providers
     * at the same time!
     */
    translatePluggableLoaderProvider.useLoader('dbStringFactory');
    translatePluggableLoaderProvider.useLoader('$dbStringProvider');

    // make sure all values used in translate are sanitized for security
    $translateProvider.useSanitizeValueStrategy('sanitize');

    // cache translation files to save load on server
    $translateProvider.useLoaderCache(true);

    /**
     *  Map the locale variants of en_US and en_UK to 'en'
     *  CS: Just an example of how to do it, remove this if you want to use full region codes (locales)
     */
    $translateProvider
    .registerAvailableLanguageKeys(angularTranslateLanguageKeys, {
        'en_US': 'en',
        'en_UK': 'en'
    })
    .use('en');

    // store the users language preference in a cookie
    $translateProvider.useLocalStorage();
}

现在在应用程序的页面上,使用以下命令测试字符串是否已加载

NOTE: The LAST loader added will overwrite previous entries in the translation, in the config we loaded the partial provider, then the dbStringFactory then the dbStringProvider So the provider should overwrite any keys provided by the factory implementation:

English is a tag in a partial file loaded from $translatePartialLoaderProvider.addPart('app');

<h3 translate>English</h3>
<h1 translate>TEXT</h1>
<h2 translate>TEXT1</h2>
<h2 translate>TEXT2</h2>

产生:

翻译成法语:

Notice Provider still shows the static string results, because if is NOT changing the result based on the passed on options.key where as the factory implementation does filter on the passed in language but is only configured to show the english translation.

如果未找到匹配项,angular-translate 到 return 原始密钥的正常行为仍然存在。

我最初遇到了与 OP 相同的问题,希望你觉得这有用。