Изменение формата даты, имен месяцев и названий недели во время выполнения вполне возможно с помощью AngularJS 1.5.9 и момента 2.17.1.
Сначала настройте исходный язык. (В этом примере конфигурация angular-translate / $ translateProvider необязательна.)
angular.module('app').config(configureLocalization)
configureLocalization.$inject = ['$translateProvider', '$mdDateLocaleProvider', 'localdb', '__config'];
function configureLocalization($translateProvider, $mdDateLocaleProvider, localdb, __config) {
// Configure angular-translate
$translateProvider.useStaticFilesLoader({
prefix: 'locale/',
suffix: '.json'
});
// get the language from local storage using a helper
var language = localdb.get('language');
if (!language || language === 'undefined') {
localdb.set('language', (language = __config.app.defaultLanguage));
}
// Set the preferredLanguage in angular-translate
$translateProvider.preferredLanguage(language);
// Change moment's locale so the 'L'-format is adjusted.
// For example the 'L'-format is DD.MM.YYYY for German
moment.locale(language);
// Set month and week names for the general $mdDateLocale service
var localeData = moment.localeData();
$mdDateLocaleProvider.months = localeData._months;
$mdDateLocaleProvider.shortMonths = moment.monthsShort();
$mdDateLocaleProvider.days = localeData._weekdays;
$mdDateLocaleProvider.shortDays = localeData._weekdaysMin;
// Optionaly let the week start on the day as defined by moment's locale data
$mdDateLocaleProvider.firstDayOfWeek = localeData._week.dow;
// Format and parse dates based on moment's 'L'-format
// 'L'-format may later be changed
$mdDateLocaleProvider.parseDate = function(dateString) {
var m = moment(dateString, 'L', true);
return m.isValid() ? m.toDate() : new Date(NaN);
};
$mdDateLocaleProvider.formatDate = function(date) {
var m = moment(date);
return m.isValid() ? m.format('L') : '';
};
}
Позже у вас может быть некоторый базовый контроллер, который следит за языковой переменной, которая изменяется, когда пользователь выбирает другой язык.
angular.module('app').controller('BaseCtrl', Base);
Base.$inject = ['$scope', '$translate', 'localdb', '$mdDateLocale'];
function Base($scope, $translate, localdb, $mdDateLocale) {
var vm = this;
vm.language = $translate.use();
$scope.$watch('BaseCtrl.language', function(newValue, oldValue) {
// Set the new language in local storage
localdb.set('language', newValue);
$translate.use(newValue);
// Change moment's locale so the 'L'-format is adjusted.
// For example the 'L'-format is DD-MM-YYYY for Dutch
moment.locale(newValue);
// Set month and week names for the general $mdDateLocale service
var localeDate = moment.localeData();
$mdDateLocale.months = localeDate._months;
$mdDateLocale.shortMonths = moment.monthsShort();
$mdDateLocale.days = localeDate._weekdays;
$mdDateLocale.shortDays = localeDate._weekdaysMin;
// Optionaly let the week start on the day as defined by moment's locale data
$mdDateLocale.firstDayOfWeek = localeData._week.dow;
});
}
Обратите внимание, что нам не нужно изменять методы $mdDateLocale.formatDate
и $mdDateLocale.parseDate
, поскольку они уже настроены на использование L-формата, который изменяется при вызове moment.locale(newValue)
.
См. документацию для $ mdDateLocaleProvider для дополнительной настройки языка: https://material.angularjs.org/latest/api/service/ $ mdDateLocaleProvider
Бонус : Вот как может выглядеть переключатель языка: