This is how I do my i18n job, it works great! It is based on a set of localized resource files that are initialized at runtime.
I18n module for storing line map and parameter input
.factory('I18n', ['$http', 'User', function($http, User) { // Resource File var LANG_FILE; // Fetch Resource File function init() { return $http.get('resources/locales/' + User.locale + '.json') .then(function(response) { LANG_FILE = response.data; }); } function lang(stringId, params) { var string = LANG_FILE[stringId] || stringId; if (params && params.length) { for (var i = 0; i < params.length; i++) { string = string.replace('%' + (i + 1), params[i]); } } return string; } return { init: init, lang: lang }; }]);
This can be initialized with a .run block.
.run(['I18n', function(I18n) { I18n.init(); }]);
And used everywhere to translate a line like this
.controller(['$scope', 'I18n', function($scope, I18n) { $scope.title = I18n.lang(some_string_id); }]);
Custom i18n DIRECTIVE for processing one-time transfers
.directive('i18n', ['I18n', function(I18n) { return { restrict: 'A', scope: {}, link: function(scope, $el, attrs) { $el[0].innerHTML = I18n.lang(attrs.i18n); } }; }]);
What can be used like this.
<div i18n="some_string_id"></div>
The user directive PLURALIZE, which corresponds to the identifiers of the lines from the resource file with the indication as a parameter.
.directive('pluralize', ['I18n', function(I18n) { return { restrict: 'A', scope: { count: '=' }, link: function($scope, $el, attrs) { var when = JSON.parse(attrs.when) , param = [$scope.count]; if (when[$scope.count]) { $el[0].innerHTML = I18n.lang(when[$scope.count], param); } else { $el[0].innerHTML = I18n.lang(when['other'], param); } } }; }]);
And you can use it like this.
<div pluralize count="{{obj.count}}" when="{1:'single_item','other': 'multiple_item'}"></div>
The String resource file will reside in the / locales / en -US.json resources and will look something like this.
{ some_string_id: 'This is in English', single_item: '%1 item', multiple_item: '%1 items' }
Other locales will have the same line identifiers with different translated texts.