Reputation: 7439
I am using Angular translate for my app localization. I'd like to dynamically change the date format depending on the user's locale.
dd/mm/yyyy
mm/dd/yyyy
How can I achieve this (cleanly) with Angular translate ?
Upvotes: 3
Views: 5435
Reputation: 7439
I finally ended using moment.js and Angular moment. Dates can be formatted to locale default with this:
<td>{{user.lastLogin | amDateFormat:'l LT'}}</td>
To change the moment locale, use the following:
amMoment.changeLocale(language);
Don't forget to import the moment locale files for the languages you wish to support:
<script src="assets/global/plugins/moment.min.js"></script>
<script src="jslib/angular-moment.min.js"></script>
<script src="jslib/moment/de.js"></script>
<script src="jslib/moment/es.js"></script>
<script src="jslib/moment/fr.js"></script>
<script src="jslib/moment/it.js"></script>
<script src="jslib/moment/pl.js"></script>
<script src="jslib/moment/ru.js"></script>
<script src="jslib/moment/zh-cn.js"></script>
And add angular moment module in your app:
var myapp = angular.module('myapp', ['angularMoment']);
Upvotes: 2
Reputation: 4533
Yeah there is a very easy way to do it.. Not sure if it's clean but can be made clean.
you can use interpolation
provided by angular-translate, the problem is you can't use function
inside interpolation string, but you can do something cool..
pass a function inside the object you're interpolating and call that function while interpolation
say you need to put in date
{{ 'date' | translate:{date:"28/01/2016"} }}
//instead of this
{{ 'date' | translate:'{date:"28/01/2016",func: func}' }}//func comes from scope.
and in your $translateProvider.translations
$translateProvider.translations('en',{
'date': "{{func(date)}}"
});
here is the plnkr
Upvotes: 1
Reputation: 3025
Maybe I am out of date, but I don't think angular-translate has anything to do with localization. So here are my solution (yet it very clean)
bower install angular-i18n
<script src="/bower_components/angular-i18n/angular-locale_YOUR-LOCALE.js"></script>
bower install angular-dynamic-locale
<script src="myPath/tmhDynamicLocale.js"></script>
your js:
angular.module('myApp', ['tmh.dynamicLocale', ...])
angular.module('myApp').controller('myController', [..., 'tmhDynamicLocale',
function… {
tmhDynamicLocale.set('en');
}
])
NOTE, made sure you check the repo's readme for usage of localeLocationPattern(string)
Upvotes: 1