【问题标题】:Dynamically load i18n Angular locale depending on select根据选择动态加载 i18n Angular 语言环境
【发布时间】:2014-06-03 15:41:58
【问题描述】:

我使用包含所有国家/地区列表的选择,并使用外部 json 文件填充。 在这个文件中,我有一个 i18n 语言环境“语言 - 国家/地区”的密钥,例如'我们'。

我在更新选择后获得了语言环境。 有没有办法从目录 https://code.angularjs.org/1.2.10/i18n/ angular-locale_XX-XX.js 动态加载 i18n 角度?谢谢你的提示

HTML

<select ng-change="updateCountry()" ng-disabled="!data.locations.countries.$resolved" ng-model="selectionCountry" ng-options="country.name for country in data.locations.countries"></select>

脚本

 .controller('MyCtrl', ['$scope','$filter', '$http', '$timeout', '$locale', function($scope, $filter, $http, $timeout, $locale) {

     $scope.data = {
    locations: {
      countries: []
    }
  };

  // set default Country
  $scope.data.locations.countries.$default = 'United States';
  $scope.data.locations.countries.$resolved = false;

  // Populate countries.json in Country Select
  $http.get('l10n/countries.json').success(function(countries) {
    $scope.data.locations.countries.length = 0;
    // actually filter is set to none. to activate choose for e.g. (countries, 'name')
    Array.prototype.push.apply($scope.data.locations.countries, $filter('orderBy')(countries, ''));
    $scope.selectionCountry || ($scope.selectionCountry = $filter('filter')($scope.data.locations.countries, {name: $scope.data.locations.countries.$default})[0]);
    $scope.data.locations.countries.$resolved = true; 
  });

// get the i18n locale for the selected option
$scope.updateCountry = function() {
var selFormat=$scope.selectionCountry.i18n;
   console.log(selFormat);
};

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    这就是我的工作

            var locale = window.navigator.userLanguage || window.navigator.language;
            // console.log(locale);
            if (locale) {
                //change the value for tests
                // locale = 'fr-FR'; 
                var smallLocale = locale.toLowerCase();
                document.write('<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.4.9/angular-locale_' + smallLocale + '.js"><\/script>');
    
            }
    

    除了控制台上有这条消息外,它工作正常

    一个解析器阻塞的跨域脚本, https://cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.4.9/angular-locale_en-us.js, 通过 document.write 调用。这可能会被浏览器阻止,如果 设备网络连接不佳。

    【讨论】:

      【解决方案2】:

      好的。我得到了解决方案:

      var imported = document.createElement('script');
      var fileImport = 'angular-locale_' + selFormat + '.js';
      imported.src = 'https://code.angularjs.org/1.2.10/i18n/' + fileImport;
      document.head.appendChild(imported);
      

      【讨论】:

      • 我已经使用它来加载正确的文件,但没有任何反应,例如日期格式没有改变,这真的适合你吗?
      猜你喜欢
      • 2019-01-13
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多