Search code examples
javascriptangularjsjsonngrouteangular-translate

Angular-translate and ngRoute $routeParams


I´m using angular-translate to add suport for 3 languages (english, portuguese and spanish) and everything is working fine.

    // config angular translate
app.config(['$translateProvider', function ($translateProvider) {
  // configures staticFilesLoader
  $translateProvider.useStaticFilesLoader({
    prefix: 'translations/locale-',
    suffix: '.json'
  });

  $translateProvider.preferredLanguage('en');
}]);

this way I have 3 files with all the translations for the 3 languages. But the problem that I am facing now is,

What if I need to translate data that comes from a json file and changes dynamically via $routeParams with ngRoute?

here is how I´ve done before getting into i18n

// MyController

app.controller('MyController', ['$scope', '$routeParams', '$http',
    function($scope, $routeParams,  $http) {
        $http.get('someFolder/' + $routeParams.itemId + '.json').success(function(data) {
            $scope.item = data;
        });
    }]);

One of the json files

{
  "id": "blue",
  "color": "Blue",
  "description": "The color blue is one of trust, honesty and loyalty"
 }

I have a folder with json files that its loaded with the ID of the item. and my html looks like this:

<dl class="dl-horizontal" ng-controller="MyController">
    <dt>{{ 'item.label.color' | translate }}</dt>
    <dd>{{ item.color }}</dd>
    <dt>{{ 'item.label.description' | translate }}</dt>
    <dd>{{ item.description }}</dd>
</dl>

I was able to translate the label of the items because its always the same across all the json files but what I actually need is to translate the values.

Is there any solution for this?

thanks in advance


Solution

  • Instead of the static files loader, take a look at the PartialLoader. This allows you to break your templates in to parts, and request each part individually.

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

    with this, you do

    $translatePartialLoader.addPart('common');
    

    that will load 'common/i18n/.json'