How to best organize translation strings in angular-translate?

半城伤御伤魂 提交于 2019-11-30 03:03:44

angular-translate supports async loading of partial language files. All partials are merged into one dictionary per language. The official documentation can be found here: http://angular-translate.github.io/docs/#/guide/12_asynchronous-loading

It supports applying a template for url templates that point to the modularised language files:

$translateProvider.useLoader('$translatePartialLoader', {  
  urlTemplate: '/i18n/{part}/{lang}.json'
});

From within your controllers, you can add language modules and refresh the data bindings like this:

angular.module('contact')
  .controller('ContactCtrl',
    function ($scope, $translatePartialLoader, $translate) {  
      $translatePartialLoader.addPart('contact');
      $translate.refresh();
    });

Of course, loading the partials can also be covered in a route's resolve phase

Alternatively, you can also look into building your own custom loader function. http://angular-translate.github.io/docs/#/guide/13_custom-loaders

This provides all the flexibility you need to combine required language modules in one shot. E.g. you could do something like this:

app.factory('customLoader', function ($http, $q) {
  // return loaderFn
  return function (options) {
    var deferred = $q.defer(); 
    var data = {
      'TEXT': 'Fooooo'
    };
    $http.get('nls/moduleA/en.json').success(function(moduleA){
      angular.extend(data, moduleA);
      $http.get('nls/moduleB/en.json').success(function(moduleB){
        angular.extend(data, moduleB);
        deferred.resolve(data);
      });
    });
    return deferred.promise;  
  };
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!