AngularJS 翻译:格式化动态日期 [英] AngularJS translate: Format dynamic dates
问题描述
使用 AngularJS 和 angular-translate 我试图在翻译文本中插入一个日期作为参数.
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>
在本地化的 json 文件中使用:
with this in a localized json-file:
(english)'MyText': 'This is the date: {{myDate}}.'
(danish) 'MyText': 'Dette {{myDate}} er datoen.'
这给了我:
(english) 这是日期:2015-04-29T00:00:00.
(丹麦语)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).
想要的结果是:
(english) 这是日期:04-29-2015.
(丹麦语)Dette 29-04-2015 er datoen.
我希望有这样的语法:
(english)'MyText': 'This is the date: {{myDate:MM-dd-yyyy}}.'
(danish) 'MyText': Dette {{myDate:dd-MM-yyyy}} er datoen.'
或者:
<p>{{ 'MyText' | translate:{{myDate:someControllerDate | translate:'MyDateFormat'}} }}</p>
与
(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)?
推荐答案
假设您有以下 angular-translate
翻译定义:
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>
today
在控制器中定义的地方,即:
Where today
is defined in controller i.e.:
$scope.today = new Date();
假设您已使用正确的语言环境加载了 angular-locale_*
,则日期将为以特定于语言/国家/地区的方式格式化.
Assuming you've loaded angular-locale_*
with correct locale the dates will be formatted in a language/country specific way.
这是一个演示.
话虽如此,Angular 内置了本地化机制 (ngLocale
)非常有限,当涉及到日期时,您可以使用 moment.js
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
这篇关于AngularJS 翻译:格式化动态日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!