#internationalising an #Angular web app
This perhaps is not the best way to internationalize (i.e. make available in multiple languages) an Angular web app, but it works well for me, both as a Web app, or as part of a Cordova / Phonegap app.
In App.js, I define the following “Constant”
angular.module(‘app’, [‘ionic’, …. ])
.constant(‘translations’, {
‘en’ :
{
‘Register’ : ‘Register’,
‘Login’ : ‘Login’,
},
‘es’ :
{
‘Register’ : ‘Registrar’,
‘Login’ : ‘Iniciar sesión’,
},
current : function()
{
lang = ‘en’;
if (navigator.languages != undefined) lang = navigator.languages[0]; else lang = navigator.language;
if (lang.indexOf(“es”) != -1 ) return this.es;
return this.en; // default en
}
})
Which effectively defines two languages “en” (English) and “es” (Spanish), and defines two variables, or strings within it “Login” and “Register”, you can see how the translation differs between English and Spanish. You can of course define more words, and more languages, this demo is just making a basic case.
Now, in order to use this in a controller, you pass it in as follows;
.controller(‘loginCtrl’, [‘translations’,‘$scope’, …..
function (translations, $scope, …) {
$scope.translations = translations.current();
Then you can refer to the translation in the template html as follows;
<a class=“button” ng-click=“login()”>{{ translations.Login }}</a>
Or in code as follows;
alert($scope.translations.Login);
This, once again is going to be used in version 1.5 of our iOS app for CloudAnsweringMachine.com