rsanchez
2014-12-12 4c13c7324a920f5cca9601154e5224e5d7484fa9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
(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));
                   }
               };
           });
})();