How to handle string localization with AngularJS and Typescript
As many of you may already know, most of the times we developers write something is because we feel the need to create. Not because the current project really requires it, but just because we feel the urge to write some code, patch something up. Especially when the project is reeeeally boring.
In my case I needed a quick and dirty way to localize strings in my AngularJS app. I know there are plenty of standard and non-standard ways to do this but this time I wanted a way to escape the boredom.
What I came up with is a simple Service that looks like this:
(yes, I’m using Typescript)
The implementation takes care of reading a very simple JSON file containing all the available cultures and the respective labels. Something like this:
The example app itself is very simple, there are just two controllers:
LanguageController acts as a simple wrapper over the ILanguageService, exposing the list of available cultures and allowing get/set for the current one. On the UI there’s just a dropdown with the cultures.
MainController instead takes care of requesting the labels from ILanguageService and $watch-ing it’s currentCulture property. When an update is detected (eg. something changed on LanguageController), the new labels are fetched from the service.