mm1975 mm1975 - 2 months ago 16
AngularJS Question

Dynamically load i18n Angular locale depending on select

I use an select with a list of all countries, populating with an external json-File.
In this File, I have a key for the i18n locale 'language - Country' for e.g. 'en-us'.

I get the locale after updating the select.
Is there a way to dynamicall load the i18n angular, coming from the directory https://code.angularjs.org/1.2.10/i18n/ angular-locale_XX-XX.js ? Thank you for your tips

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

Answer

O.k. I got the solution:

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