code everywhere

AngularJS JSON based localization service

posted on March 14, 2014, 4:53 pm in js, angularjs

This AngularJS service will allow you to localize your app using JSON language files.

The Service

app.service('localization', ['$http', function($http) {
    var 
lang 0;
    var 
languageFile;
    var 
customLabels = {};

    function 
setLang(code) {
        if (
code === undefined || code === null)
            return 
lang;

        
code code.toLowerCase();
        
lang code;
        
$http.get('path/to/lang/' code '.json').then(function(res) {
            
languageFile res.data;
            return 
true;
        });
    }

    function 
lookUpKey(key) {
        if (
customLabels[lang] !== undefined && customLabels[lang][key] !== undefined)
            return 
customLabels[lang][key];

        if (!
angular.isDefined(languageFile))
            return 
"...";
        else if (!
angular.isDefined(languageFile[key]))
            return 
"err:" key;
        else
            return 
languageFile[key];
    }

    function 
update(langkeyvalue) {
        if (
customLabels[lang] === undefined)
            
customLabels[lang] = {};
        
customLabels[lang][key] = value;
    }

    return ({
        
key      lookUpKey,
        
lang     setLang,
        
updateupdate
    
});
}]);

Example Usage

Here's how you can use the service.

// set a language
localization.lang("en");

// get set language
var currentLang localization.lang();

// Get a translated string
var message localization.key('hello_key') + name;

// Update a value (non-persistent)
localization.update("en""hello_key""hello you ");

The language file is a key => value object, it should look like:

// example 'en.json' file
{
    
"hello_key" "Hello there "
}

recent posts

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy