根据select动态加载i18n Angular语言环境

时间:2014-06-03 15:41:59

标签: javascript angularjs

我使用带有所有国家/地区列表的select,使用外部json-File填充。 在这个文件中,我有一个用于i18n语言环境的键 - 国家'例如' EN-US'

更新select后我得到了语言环境。 有没有办法动态加载i18n角度,来自目录https://code.angularjs.org/1.2.10/i18n/ angular-locale_XX-XX.js?感谢您的提示

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>

SCRIPT

 .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);
};

2 个答案:

答案 0 :(得分:0)

这就是我的工作

        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>');

        }

除了控制台上有此消息

外,它工作正常
  

Parser-blocking,cross-origin脚本,   https://cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.4.9/angular-locale_en-us.js,   通过document.write调用。如果,浏览器可能会阻止此操作   设备网络连接不良。

答案 1 :(得分:-2)

O.k。我得到了解决方案:

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);