Adding i18n support to your Angular Applications


For adding i18n support to your Angular.js based applications you could find angular-translate module to be very useful. This is really good module to use for that purpose.

This post is about using that module as a base and going a bit further by encapsulating all i18n related logic completely into its own separate module with minimal impact to your application’s config method.

About the module

You can find the source code for the module on this repository. Also the example small application using it can be found here.

In order to use url.i18n in your applications you will first need to downlaod and add angular-translate.js as a dependency to your application.

I am usually using bower, so for me it required this 2 things: 1) Adding following line to my bower.json file:

"angular-translate": "~2.0.1"

After that you should be including the library specific files to your index.html page (or whatever root page of your project). This would also mean that you would have copied the content of lib folder within a specific location in your application (that specific location depends on your application structure and the way you are laying out your modules).

    <script src="../lib/index.js"></script>
    <script src="../lib/constants.js"></script>
    <script src="../lib/providers/translation-provider.js"></script>
    <script src="../lib/lang/sr.js"></script>
    <script src="../lib/lang/de.js"></script>
    <script src="../lib/lang/en.js"></script>

I like my modules to have clear files separation hence you’ll see everything in its own file. I find this especially usefull for a large teams. But you could easily use only 1 file and concatenate all my files within it. I usually use grunt for building so I have separate tasks for doing that for production versions.

The next step is to configure your angular.js application (main angular module) to use url.i18n. This means you should add url.i18n as a dependency to your application – something like this:

angular.module('myApplication', ['url.i18n'])

With this you’re good to go with using this module for i18n support within your application. The only thing to do is change your templates and global controller to be able to switch languages. Check out example folder for an example (deployed here).

If you want to set a specific language as a default language you can easily do that by adding following line to your main application’s config handler function (see example for reference):

TranslationProvider.setPreferredLanguage('de');

Your company needs help from an expert?  Feel free to contact me.

 

Links

Leave a comment