Chapter 10
In the current version of AngularJS a locale needs to be selected
upfront, before an application is initialized. The selected locale can't
be switched on the fly, and requires that an application is re-initialized
with another ngLocale module.
Given how the module system operates in the current version of AngularJS our best
option for switching locale is to re-initialize an application by redirecting users to a
URL with a new locale specified. A redirect means that the whole state in a browser
will be lost. Fortunately, the AngularJS deep linking feature will take a user to the
same place in an application after locale change.
To switch a locale by redirecting users we will have to prepare a string for a new
URL first. We can do this easily using the API exposed by the $location service.
For example, given the current URL: http://host.com/en-us/admin/users/list
and a desired target URL http://host.com/fr-ca/admin/users/list.
We could write the following switchLocaleUrl function:
$scope.switchLocaleUrl = function(targetLocale) {
return '/'+targetLocale+'/'+$location.url();
};
The switchLocale function just shown would calculate a URL taking users to a
route equal to the current one, but in a specified targetLocale. This function could
be used in the standard tag to take users to a site with a new locale selected:
<a ng-href="switchLocaleUrl('fr-ca')" target="_self">Français</a>
Custom formatting for dates, numbers, and currencies
Some of the AngularJS filters can deal with locale-specific content by default. For
example, as seen at the beginning of this chapter, the date filter can be supplied with
a locale-dependent, named format, for example, {{now | date:'fullDate'}}. The
exact mapping from the fullDate string to the actual format is defined in a file with
locale-specific settings under the $locale.DATETIME_FORMATS.fullDate key. As an
example, for the fr-ca locale the fullDate format is equivalent to: EEEE d MMMM y.
The default formats are usually exactly the ones we would expect for a given
language and a country, but we might want to slightly adjust certain formats for
some locales. This can be easily achieved by creating a decorator over a filter.