I saw some i18n plugins for Angular, but I don't want to reinvent the wheel. i18next is a good library, and therefore I intend to use it.
I created the i18n directive, which simply calls the i18n library:
define(['app', 'jquery', 'i18n'], function(app, $, i18n) {'use strict';
app.directive('i18n', function() {
return function($scope, elm, attrs) {
attrs.$observe('i18n', function(value) {
if ($.fn.i18n) {
$(elm).i18n();
}
});
};
});
});
On my page, I can change the language on the fly:
<a ng-repeat="l in languages"> <img ng-src="images/{{l.id}}.png" title="{{l.label}}" ng-click="setLanguage(l.id)" /> </a>
Now my main controller is defined in the html tag:
define(['app', 'i18n', 'jquery'], function(app, i18n, $) {'use strict';
return app.controller('BuilderController', ['$scope', '$location',
function BuilderController($scope, $location) {
$scope.$watch(function() {
return $location.path();
}, function() {
$scope.setLanguage(($location.search()).lang || 'en');
});
$scope.languages = [{
id : "en",
label : "English"
}, {
id : "fr",
label : "Français"
}];
$scope.$watch('language', function() {
$location.search('lang', $scope.language);
i18n.init({
resGetPath : 'i18n/__lng__/__ns__.json',
lng : $scope.language,
getAsync : false,
sendMissing : true,
fallbackLng : 'en',
debug : true
});
$(document).i18n();
});
$scope.setLanguage = function(id) {
$scope.language = id;
};
}]);
});
How it works: a language observer initializes the i18n object with a new locale, and then updates all the DOMs using the iQn jquery extension. Outside of this special event, my directive just works fine for all other tasks (templates that use the i18n directive and display at a later time).
While it is working fine, I know that I should not manipulate the DOM inside the controller, but since nothing happens in the end, I did not find a better solution.
, Angular DOM, , , .
$scope. $Apply(): ,
Scope.onReady .
, Angular, , .