How to translate a date object using angular-translate?

I have a list of dates in my view powered by my controller. I use angular-translate to control the localization in my application, but don't know how to handle the date object.

My HTML looks like this:

<div ng-repeat="date in nextDates"> <div class="day">{{date | date: 'EEEE'}}</div> </div> 

This code displays the list per day: Monday, Tuesday, ... based on date , which is the date object.

My first attempt was to use moment.js, which is already used in this project, and does an excellent job with i18n. It works, but it was difficult for me to update it when the lang is changed by the user , since moment.js is not related to angular -translate.

I tried to implement it on my controller, using the event to update my variable, but it didn’t work. I would like to keep the date of the object in my view, instead of having an instant object, I am sure there is a way not to implement it manually.

 $scope.$on('translationChanged', function(event, lang) { ... }); 

I would like to know if there is an easy way to solve this problem. My only idea is to create a key for the transfer, for example, DAY.0 for Monday, DAY.1 and translate it yourself, but it sounds cheap. moment.js seems perfect to work, but then how to link it to angular-translate?

Thank you for reading.

+6
source share
1 answer

So, after some research, I found a library on github called angular-moment that works fine for me.

First I import as js + locale files

 <script src="bower_components/moment/moment.js"></script> <script src="bower_components/angular-moment/angular-moment.js"></script> <script src="bower_components/moment/locale/fr.js"></script> <script src="bower_components/moment/locale/de.js"></script> <script src="bower_components/moment/locale/it.js"></script> 

Then I set the locjs variable while setting the application mode

 var core = angular.module('app.core').config(configLang); configLang.$inject = ['moment']; /* @ngInject */ function configLang(moment) { moment.locale('en'); } 

Then I can start using amFormat directive in my templates directly on my Date object

 <div ng-repeat="date in nextDates"> <div class="day">{{date | amDateFormat:'dddd'}}</div> </div> 

If I want to change the language in my application, I just use moment.locale (String); and my view is automatically updated.

 $rootScope.$on('$authenticationStateChanged', function(event, userData, isAuthenticated) { moment.locale(userData.currentLanguage.toLowerCase()); }); $scope.$on('translationChanged', function(event, lang) { moment.locale(lang.toLowerCase()); }); 

Then I can access the full power of the .js moment in an angular: D application.

+7
source

Source: https://habr.com/ru/post/985494/


All Articles