Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get localized templates (templateUrl) in routing with AngularJS

Tags:

angularjs

There is a use case that is quite popular when building international web application:

There are localized templates for each culture, with name convention like 'en_US/name.html', 'ru_RU/name.html' etc.

User's locale setting could be get only after user logged (or user can select locale).

So the best option that I found is to provide localization value using DI (so it could be updated form anywhere - or when I recieve response from backend with user config, or when user select something).

But routing could be configured only in configuration step, where 'values' could not be injected. So you can't inject locale config and add templateUrl according to that value.

Here is a Plnkr example do illustrate my solution.

Only other solution I see, is to modify private array of routes (using $route.routes[]), but it sounds like ugly hack.

Is there are other solutions to implement this common use case of using localized templates?

like image 456
Valentyn Shybanov Avatar asked Dec 27 '12 11:12

Valentyn Shybanov


1 Answers

There might be ways to do this as you want, like overriding templateCache instead of modifying routing but I'm going to approach this issue differently.

In your approach, as your site grows it would be very difficult to maintain (at least) 2 copies of templates. If you support more languages, then you'd be in trouble much shorter.

I'd create a service which holds dictionary like objects for languages.

angular.module("myApp", [])
       .factory("Internationalization", function () {
           var dict: {
               en_US: {
                   hello: "Hello,"
               },
               fr_FR: {
                   salut: "Salut,"
               }
           };
           var get = function (locale, key) {
               return formatdict[locale][key];
           }
           return {get: get};
       });

Then you can inject the service in the controller and attach it to scope.

This should help you getting started, you might want to check this out if you want string.format support.

like image 154
Umur Kontacı Avatar answered Oct 12 '22 12:10

Umur Kontacı