How to get localized patterns (templateUrl) in routing using AngularJS

There is a usage example that is quite popular when creating an international web application:

There are localized templates for each culture with the conditional name "en_US / name.html", "ru_RU / name.html", etc.

The user language parameter can be obtained only after the user logs in (or the user can select the locale).

So, the best option I found is to provide a localization value using DI (so that it can be updated anywhere - either when I get a response from the backend with user configuration or when the user selects something).

But routing can only be configured at the configuration stage, where β€œvalues” cannot be entered. Thus, you cannot enter the locale configuration and add templateUrl according to this value.

Here is a Plnkr example that illustrates my solution.

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

Are there other solutions to implement this common use case for localized templates?

+6
source share
1 answer

There may be ways to do this the way you want, for example overriding templateCache instead of changing routing, but I will look at this problem differently.

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

I would create a service that stores the dictionary as 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 enter the service into the controller and attach it to the area.

This will help you get started, you can check this if you want string.format support.

+1
source

All Articles