Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to translate Angular-UI-Bootstrap datepicker?

The documentation for the datepicker (Angle-UI-BootStrap) reports:

Everything is formatted using the date filter and thus is also localized.

Checking the documentation for the date filter can have access to the concept of i18n and i10n for AngularJs. However, the two approaches which are provided, can not be used in my application. The two approaches are:

  1. Pre-bundled rule sets
  2. Including locale js script in index.html page

In my application, I check the language of the client after he had performed login. So my index.html page is already created and configured.

There is no other way to translate the datepicker? A dynamically way... something like changing a value of the $scope that alters the interface performing the translation of the component?

Here's a plunker demonstrating the approach of introducing in the index.html the translation for pt-BR.

Update: I asked this question in an issue of the Angle-UI-Bootstrap, and here is the response I received from @bekos:

@ThCC The real problem is that you cannot change your $locale during runtime, or at least I don't know of a way to do this. Even if you solve the problem with the datepicker, you will still have problem in every other filter that is locale dependent, like currency. I think it is better to ask a more general question in the AngularJS issues.

If anyone has another solution is always welcome. If I get a solution I will return here.

like image 664
ThCC Avatar asked Sep 30 '13 12:09

ThCC


2 Answers

Someone said [The real problem is that you cannot change your $locale during runtime]. In fact you can. You can see a working plunker here.

like image 58
Serge Tahé Avatar answered Nov 15 '22 06:11

Serge Tahé


You can create your own directive like this:

angular
    .module('myApp.common')
    .directive('datepickerPopupWrap', datepickerPopupWrap);

datepickerPopupWrap.$inject = ['$rootScope'];

function datepickerPopupWrap($rootScope, $compile) {

    return {

        restrict: 'A',
        require: 'ngModel',

        link: function($scope, $element, attrs, ngModel) {
            // Force popup rerender whenever locale changes
            $rootScope.$on('localeChanged', ngModel.$render);
        }
    };

}

The directive name must be datepickerPopupWrap, so it's executed together with the default ui-bootstrap directive that renders the popup.

Then, whenever you change the locale with angular-dynamic-locale, do this:

tmhDynamicLocale.set(languageKey).then(function() {

    // Set the language in angular-translate
    $translate.use(languageKey);

    // Broadcast the event so datepickers would rerender
    $rootScope.$broadcast('localeChanged');
});
like image 31
npe Avatar answered Nov 15 '22 08:11

npe