How to translate a date object using angular-translate?

邮差的信 提交于 2020-01-02 03:42:23

问题


I have a list of date in my view, powered by my controller. I am using angular-translate to manage localisation in my all application but do not know how to deal with date object.

My HTML looks like this :

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

This code display a list a day : Monday, Tuesday, ... based on date which is a date object.

My first try was to use moment.js which is already used in this project, and deal really well with i18n. It works, but I had a lot of difficulty to update it when lang is changed by user since moment.js is not related to angular-translate.

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

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

I would like to know if there is an easy way to solve this issue, my only idea is to generate a key for translation like DAY.0 for Monday, DAY.1 and translate it by myself but it sounds cheap. moment.js seems perfect for the job, but then how to link it with angular-translate ?

Thanks for reading.


回答1:


OK so after some research I found a library on github called angular-moment which work fine for me.

First I import both js files + locale

<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 up momentjs locale variable during my app mode config

var core = angular.module('app.core').config(configLang);

configLang.$inject = ['moment'];

/* @ngInject */
function configLang(moment) {
    moment.locale('en');
}

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

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

If I want to change language in my app, 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());
});

I can then access all the power of moment.js in my angular app :D.



来源:https://stackoverflow.com/questions/29742365/how-to-translate-a-date-object-using-angular-translate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!