Building AngularJS Web Applications for an International Audience
Using filters
Assuming that we've got JSON structure with translated strings like:
{
'greetings.hello': 'Hello'
...
}
We could imagine writing a filter (let's call it i18n) to be used as follows:
<span>{{'greetings.hello' | i18n}}, {{name}}!</span>
Writing a basic version of the i18n filter wouldn't be difficult, and we could start off
by sketching the code as shown in the following code:
angular.module('i18nfilter', ['i18nmessages'])
.filter('i18n', function (i18nmessages) {
return function (input) {
if (!angular.isString(input)) {
return input;
}
return i18nmessages[input] || '?'+input+'?';
};
});
The i18 filter would rely on a set of translated messages (i18nmessages). The
messages themselves could be declared as a value is a separate module, for example:
angular.module('i18nmessages', [])
.value('i18nmessages', {
'greetings.hello': 'Hello'
});
The i18n filter shown here is very simple, and there is plenty of room for extensions
and improvements: loading translated strings via $http service with caching,
switching locale on the fly and so on. While the presented i18n filter seems
to be working well, and we could spend time elaborating it further, if there is
performance-related problem with the filter-based approach to translations.
By turning static text "Hello" embedded in HTML into a filtered expression
({{'greetings.hello' | i18n}}) we've introduced one more expression to
be evaluated by AngularJS. As we are going to see in Chapter 11, Writing Robust
AngularJS Web Applications is strongly correlated with a number of expressions
that need to be watched and evaluated by the framework. Adding a new watch
expression for each individual string is wasteful, and might slow down your
application to unacceptable levels.