Mastering Web Application

(Rick Simeone) #1
Chapter 10

If we need to support multiple languages we can't simply hard-code a message's
text in the JavaScript code. Instead we need to be able to retrieve a localized and
parameterized message based on its key. For example, calling:


localizedMessages.get('crud.user.remove.success', {id: 1234})

It should return a message that could look like "A user with id '1234' was removed
successfully." in en-us and "Użytkownik z identyfikatorem '1234' został usunięty." in
pl-pl (Polish in Poland).


Writing a service that would look up a message based on its key and the current
locale is of no use. The only difficulty that we are facing here is delays in handling
parameters inside localized strings. Fortunately, we can lean on AngularJS here,
and re-use the $$interpolate service; the same one that AngularJS uses to handle
interpolation directives in its templates. This would allow us to specify localized
messages as:


"A user with id '{{id}}' was removed successfully."

The sample SCRUM application has a complete implementation of the localization
service based on the idea just described. A sketch of this implementation is presented
here as well as it is very simple:


angular.module('localizedMessages', [])
.factory('localizedMessages', function ($interpolate, i18nmessages) {

var handleNotFound = function (msg, msgKey) {
return msg || '?' + msgKey + '?';
};

return {
get : function (msgKey, interpolateParams) {
var msg = i18nmessages[msgKey];
if (msg) {
return $interpolate(msg)(interpolateParams);
} else {
return handleNotFound(msg, msgKey);
}
}
};
});
Free download pdf