• Home

Dynamic locale change with Ionicframework

Loading locales in a AngularJS project is easy but quite limited. You can load locales like any other javascript asset but only one at starting time.

So I decided to find a way to load several angularjs locales in my application. The idea was to select (or to detect if you wish) the desired locale, display locales (or currencies in my case) in a select box and once selected, update the content in the window (currency, dates, symbol, currency position...)

I found a lot of help with the angular-dynamic-locale project from Lucas Mirelmann and I easily apply his methods in my code.

First you need to create a blank Ionic project with ionic start myApp blank

Then edit the app.js, we are going to add a few modules to it :

  • add tmh.dynamicLocale to the module section
  • we need to tell dynamicLocale where the i18n files are. You can drop them in a i18n/ folder in your project but I prefered to query angularjs servers (even if I think it is not a good idea, it's not a CDN, but it is for example purposes) :
     .config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider, tmhDynamicLocaleProvider) {
  • we need to create a controller for our data to be exported to the view :

.controller('indexCtrl', function($rootScope, $scope, tmhDynamicLocale, $locale) {

$scope.amount = "10";
$scope.currencies = {
    'fr-fr': 'French',
    'en-us': 'US' };
$rootScope.model = {currencySelected: 'en-us'};
$rootScope.$locale = $locale;
$rootScope.changeLocale = tmhDynamicLocale.set;

  • this controller is quite simple, I defined an currency amount I will use with a currency filter. The list of currencies is also quite simple, you can add as much locale files as you want.
  • take a look at $rootScope.model wich is the default settings you will need to set for your app. In a real app I worked on I stored the default and saved locale settings in localeStorage, that may be a good hint for your projects...
  • tmhDynamicLocale.set is setting the locale and reloading the scope.

Now the index.html :

<ion-content ng-controller="indexCtrl">
    <div class="list">
        <div class="item item-input item-select">
          <div class="input-label">
            Select locale
          <select ng-model="model.currencySelected" ng-options="key as value for (key, value) in currencies" ng-change="changeLocale(model.currencySelected)"></select>
        <div class="item">
          <p>An amount of {{amount | currency}}</p>
          <p>A date {{0 | date}}</p>

  • don't forget to add the filters to your data (here : currency, date...)

You can find the full github repo for this example here : https://github.com/lennycartier/angularjs-ionic-snippets/tree/master/ionic-angular-dynamic-locale

Print Email