Dynamic locale change with Ionicframework

Written by lenny cartier.

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 :

.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;

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>

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