admin管理员组

文章数量:1406007

i'm working on an mobile app with Angular Cordova and Ionic. I want to use in my app multiple traduction files. Like :

  • menu-fr.json
  • faq-fr.json
  • local-fr.json

i'm using this code :

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

My question is how to load multiple files ? i searched a lot , but i found nothing.

Thanks in advance

i'm working on an mobile app with Angular Cordova and Ionic. I want to use in my app multiple traduction files. Like :

  • menu-fr.json
  • faq-fr.json
  • local-fr.json

i'm using this code :

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

My question is how to load multiple files ? i searched a lot , but i found nothing.

Thanks in advance

Share Improve this question asked Feb 8, 2016 at 14:37 JeffreyJeffrey 4722 gold badges10 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

You may also find the angular-translate-loader-pluggable package useful, partial loader still replaces the loader provider instead of allowing multiple loaders for any given module.

Pluggable loader then bees a sort of merged translation provider. It will merge the results of all the loaders that have been configured.

I use the pluggable loader to allow language files per module, as well as a database driven source.

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();
}

Now on a page in the app, use the following to test that strings are loaded

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>

Produces:

Translating to French:

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.

The normal behaviour of angular-translate to return the original key if no match was found is still observed.

I initially struggled with the same issues as OP, I hope you find this useful.

You can use partial loader : https://github./angular-translate/bower-angular-translate-loader-partial

see How to best organize translation strings in angular-translate? for a sample code

本文标签: javascriptAngular translate multiple json filesStack Overflow