Using AngularJS and angular-translate I am trying to insert a date as parameter in a translated text.
The basic task is documented by the translate package:
<p>{{ 'MyText' | translate:{myDate:someControllerDate} }}</p>
with this in a localized json-file:
(english)'MyText': 'This is the date: {{myDate}}.'
(danish) 'MyText': 'Dette {{myDate}} er datoen.'
This gives me:
(english) This is the date: 2015-04-29T00:00:00.
(danish) Dette 2015-04-29T00:00:00 er datoen.
The problem: I would like to format the date to match the language (or culture, but for now the language will be good enough).
The desired result is:
(english) This is the date: 04-29-2015.
(danish) Dette 29-04-2015 er datoen.
I was hoping for a syntax along these lines:
(english)'MyText': 'This is the date: {{myDate:MM-dd-yyyy}}.'
(danish) 'MyText': Dette {{myDate:dd-MM-yyyy}} er datoen.'
Or perhaps:
<p>{{ 'MyText' | translate:{{myDate:someControllerDate | translate:'MyDateFormat'}} }}</p>
with
(english)'MyDateFormat': 'MM-dd-yyyy'
(danish) 'MyDateFormat': 'dd-MM-yyyy'
Is there a way to achieve the desired result, preferably without having to format the date inside the controller (keeping logic and view separated)?
Assuming you have following angular-translate
translations definitions:
//de
"with_date": "German: {{date|date:'short'}}"
//en
"with_date": "English: {{date|date:'medium'}}"
Then inside a view you can do:
<h1>{{ 'with_date'|translate:{date:today} }}</h1>
Where today
is defined in controller i.e.:
$scope.today = new Date();
Assuming you've loaded angular-locale_*
with correct locale the dates will be formatted in a language/country specific way.
Here's a demo.
Having said that localization mechanism built into angular (ngLocale
) is very limited and when it comes to dates you can accomplish wonders with moment.js
来源:https://stackoverflow.com/questions/29937780/angularjs-translate-format-dynamic-dates