(function() { 'use strict'; /* * Catalogs module */ angular.module('i18n', []) .service('$L', ['$http', function ($http) { var url_tpl = '/lang/messages_{0}.json'; var _defaultLang = 'en'; var _currentLang = 'en'; var _messages = null; /** * It works similar to MessageFormat in Java */ var format = function() { var args = arguments; return this.replace(/\{(\d+)\}/g, function() { return args[arguments[1]]; }); }; this.setLocale = function(newLoc) { _currentLang = newLoc; if (_currentLang === defaultLang) _messages = null; else { $http.get(format.apply(url_tpl, [newLoc])).success(function(data) { _messages = data; // TODO: Launch event ??? }); } } /** * It accepts direct messages and templates: * { * "hello": "hola", * "Hello {0}!!: "Hola {0}!!" * } * $L.get('hello'); // This returns "hola" * $L.get('Hello {0}!!', 'John'); // This returns: "Hola John!!" if languaje is spanish */ this.get = function(msg) { if (!_messages || !_messages[msg]) { if (arguments.length === 1) return msg; var params = Array.prototype.slice.call(arguments, 1); return format.apply(msg, params); } if (arguments.length === 1) return _messages[msg]; var params = Array.prototype.slice.call(arguments, 1); return format.apply(_messages[msg], params); } var that = this; String.prototype.$i18n = function() { var args = [this]; Array.prototype.push.apply(args, Array.prototype.slice.call(arguments, 0)); return that.get.apply(that, args) }; }]) .directive( 'i18n', function($L) { return { restrict : 'A', // only activate on element attribute require : '', link : function(scope, element, attrs) { var txt = attrs.i18n || element.text(); element.text($L.get(txt)); } }; }); })();