Angularjs and $locale

Can I set $locale for some application manually?

Is it possible that only way to support locals is to include localization file from angular library for current locale. What if there are multiple cultures? In that case I have to load localization files dynamically? What am I missing?


Solution 1:

You can load the locale you want into localStorage, then refresh the page. Have the script below load the i18n file you need. Changing the locale on the fly isn't supported yet.

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script>
var locale = JSON.parse(localStorage.getItem('locale'));
if (locale) {
    document.write('<script src="scripts/i18n/angular-locale_'+locale+'.js"><\/script>');
}
</script>

Solution 2:

I've built an angular module that takes care about i18n. AngularJS support for i18n is pretty primitve, if you want to have more control and also be more flexible, checkout angular-translate - http://angular-translate.github.io/

Let me know, if I can help out!

Solution 3:

For anyone looking for dynamic localization today angular-dynamic-locale does a great job.

Solution 4:

I struggled with the same issues, read all the answers here and introduced i18n/l10n in my project. This are my outcomes:

  • angular-translate (http://angular-translate.github.io) is a perfect way to localize your content (custom-strings). But it does NOT translate angular's date, currency or number-filters.
  • Angular has a built-in mechanism to localize date, currency or number-filters. Translations for supported locales can be found here https://github.com/angular/angular.js/tree/master/src/ngLocale, the angular-guide is located at https://docs.angularjs.org/guide/i18n
  • The problem with angular's built-in mechanism: it's not that easy to change the locale at run time! This is where https://github.com/lgalfaso/angular-dynamic-locale comes into play. It allows you to change the language at run time pretty easily.

So the solution is to use both projects, angular-translate and angular-dynamic-locale.

Solution 5:

Honestly, the $locale service in angular is pretty primitive still. It's really good, but it seems to lack flexibility in this area. The biggest issue is that even if you switch your locale by dynamically reloading the proper locale file, things like the date filter won't know you've changed it because they're registering their locale information when they're set up. So you have a couple of choices currently: 1. Reload the page with the selected locale... or 2. Write your own Locale Provider and Filters that use it.

It might be possible create a service that would dynamically load the proper script file, reinitialize all affected filters and services, then refresh the views, but I'm not really sure what all that would involve at this point.