Search code examples
angularjsjsonfilternestedangular-translate

angular-translate nested JSON and filter


When using angular-translate I can filter my strings like so:

<ANY>{{'TRANSLATION_ID' | translate}}</ANY>

It works very well with the following flat JSON:

 {
  TRANSLATION_ID: 'A value',
};

However, I can't figure out how to get it to work using nested translations:

<ANY>{{'NAMESPACE.TRANSLATION_ID' | translate}}</ANY>

And the nested JSON:

{
    "NAMESPACE": {
         "TRANSLATION_ID": "A value"
    }
};

I am successfully loading the translation using $translateProvider.useStaticFilesLoader({prefix: 'i18n/locale-', suffix: '.json'});, and I make use of other functions of the provider such as $translateProvider.addInterpolation('$translateMessageFormatInterpolation');.

The documentation shows examples of nested translation using the service directly, but not the filter.

I found a possibly related issue here. First of all, using the code in the JSFifddle breaks the $translateProvider functions (I got it somehow fixed by extending the replacing variable like so: $TranslateProvider = angular.extend(m, $TranslateProvider); after injecting $translateProvider as m and add pascalprecht.translate as a module dependency, and add var declarations to be able to 'use strict') - so right off the bat it doesn't seem to be a solid solution.

With that JSFiddle code, I got the directive to work, at least for non-nested cases (which are fine and all, but not what's needed here, so I didn't bother testing the nested cases) but not the filter (which I need working for both nested and non-nested translations).

It seems to me namespaced translations should be a pretty big deal, and therefore should be available for all the 3 translation methods (service, directive and filter).

"service" method is rather limited ($translate service doesn't provide a two-way data binding which means more code to listen to events - see doc - and, well, the fact that loading all the interface's string translation in the app's controller/service seems to be a pretty bad practice ; views/templates are here for that if I'm not mistaken).

Has anyone found a solution to that, or is that angular-translate nested JSON works only for the service?


Solution

  • I know where I messed up now - the dreadful end comma in my nested translation:

    {
        "NAMESPACE": {
             "TRANSLATION_ID": "A value",
             "ANOTHER_ID": "Another value",
        }
    };
    

    So, yeah, totally unrelated.