javascriptangularjsangular-strap

How to change dynamic language in angular-strap datepicker?


I use angular-strap datepicker in my project. Unfortunately, I didn't find there opportunity for dynamic changing locale. I need to redraw datepicker on every $localeChangeSuccess, but I don't know how to do it. Plugin defines locale due to service $locale, but it defines only once on init stage.


Solution

  • Well, unfortunally angular-strap doesn't watch $locale changes. Initializing angular-strap with a specific $locale works very well but once the locale changed, angular-strap does not rerender his components. I could make it work with some tricks but this solution is not the best because its depending on $timeout's and "force render stuff". Please check this fiddle. It would be much better to create a feature request at GitHub and make angular-strap rerender when $locale changed.

    View

    <div ng-controller="Ctrl" class="padded">
        <select name="language" 
                ng-model="language" 
                ng-options="k as v for (k, v) in languages" 
                ng-change="changeLanguage(language)"></select>
        <input type="text" class="form-control" 
                ng-if="!someChange" 
                ng-model="myDate" 
                placeholder="Until" bs-datepicker>
        <div class="padded">Selected date: {{ myDate | date:'shortDate'}}</div>
    </div>
    

    AngularJS Application

    angular.module('calendar', [
      'mgcrea.ngStrap.datepicker',
      'tmh.dynamicLocale'
    ])
    .config(function (tmhDynamicLocaleProvider) {
      tmhDynamicLocaleProvider.localeLocationPattern('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/i18n/angular-locale_{{locale}}.js');
    })
    .controller('Ctrl', function($scope, tmhDynamicLocale, $timeout) {
    
      $scope.myDate = new Date();
      $scope.someChange = false;
      $scope.language = 'en-gb';
      $scope.languages = {
        'en-us': 'English (USA)',
        'en-gb': 'English (Great Britain)',
        'de-de': 'Deutsh (Deutsh)'
      };
    
    
      $scope.changeLanguage = function (language) {
    
        //set new language
        tmhDynamicLocale.set(language);
    
        //store selected date 
        var saveDate = angular.copy($scope.myDate);
    
        $timeout(function () {
          $scope.someChange = true;
          $timeout(function () {
            $scope.someChange = false;
            $scope.myDate = saveDate;
          }, 150);
        }, 150);
      }
    });