如何在 angular-strap datepicker 中更改动态语言?

How to change dynamic language in angular-strap datepicker?

我在我的项目中使用 angular-strap datepicker。不幸的是,我没有找到动态更改语言环境的机会。我需要在每个 $localeChangeSuccess 上重绘日期选择器,但我不知道该怎么做。由于服务 $locale,插件定义了语言环境,但它只在 init 阶段定义了一次。

嗯,不幸的是angular-strap doesn't watch $locale changes. Initializing angular-strap with a specific $locale works very well but once the locale changed, angular-strap does not rerender his components. I could make it work with some tricks but this solution is not the best because its depending on $timeout's and "force render stuff". Please check this fiddle。最好在 GitHub 创建功能请求并在 $locale 更改时使 angular-strap 重新呈现。

查看

<div ng-controller="Ctrl" class="padded">
    <select name="language" 
            ng-model="language" 
            ng-options="k as v for (k, v) in languages" 
            ng-change="changeLanguage(language)"></select>
    <input type="text" class="form-control" 
            ng-if="!someChange" 
            ng-model="myDate" 
            placeholder="Until" bs-datepicker>
    <div class="padded">Selected date: {{ myDate | date:'shortDate'}}</div>
</div>

AngularJS申请

angular.module('calendar', [
  'mgcrea.ngStrap.datepicker',
  'tmh.dynamicLocale'
])
.config(function (tmhDynamicLocaleProvider) {
  tmhDynamicLocaleProvider.localeLocationPattern('https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/i18n/angular-locale_{{locale}}.js');
})
.controller('Ctrl', function($scope, tmhDynamicLocale, $timeout) {

  $scope.myDate = new Date();
  $scope.someChange = false;
  $scope.language = 'en-gb';
  $scope.languages = {
    'en-us': 'English (USA)',
    'en-gb': 'English (Great Britain)',
    'de-de': 'Deutsh (Deutsh)'
  };


  $scope.changeLanguage = function (language) {

    //set new language
    tmhDynamicLocale.set(language);

    //store selected date 
    var saveDate = angular.copy($scope.myDate);

    $timeout(function () {
      $scope.someChange = true;
      $timeout(function () {
        $scope.someChange = false;
        $scope.myDate = saveDate;
      }, 150);
    }, 150);
  }
});

我尝试了使用 ng-if 的解决方案,但它给我带来了副作用,即在时间选择器中进行一次选择后 ngModel 停止更新。

我想出了另一种无需删除元素即可工作的方法:

我没有给模型一个日期,而是给它一个像这样的对象:

$scope.pickerModel = { date: myDate, language: myLang }

并像这样更改 angular-strap 代码:

转到:

controller.$formatters.push(function (modelValue) function... 行: 3774

并更改 "else" 来自:

date = new Date(modelValue);

date = new Date(modelValue.date);
if (modelValue.language) {
   options.language = modelValue.language;
}

就是这样!