[AngularJS] gettext-like i18n Solution


Client side gettext-like Internationalization (i18n) via AngularJS. Alternative solution via Directives, see [2].

Demo

Source code:

index.html | repository | view raw
 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
<!doctype html>
<html ng-app="demoGettext">
<head>
  <meta charset="utf-8">
  <title>AngularJS gettext i18n Demo</title>
</head>
<body>

<div>
  <button ng-click="i18nLocale = 'en'">English</button>
  <button ng-click="i18nLocale = 'zh_TW'">傳統中文</button>
  <button ng-click="i18nLocale = 'vi_VN'">Tiếng Việt</button>
</div>
<br>
<div>
  <span>{{_("Home")}}</span>
  <br>
  <span>{{_("Canon")}}</span>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="ngGettextData.js"></script>
<script src="ngGettext.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js | repository | view raw
1
2
3
4
5
6
7
8
'use strict';


angular.module('demoGettext', ['gettext', "gettextData"]).
  run(['$rootScope', function($rootScope) {
    // default locale is English
    $rootScope.i18nLocale = "en";
  }]);
ngGettext.js | repository | view raw
 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
'use strict';


angular.module('gettext', ['gettextData']).
  run(['$rootScope', 'i18nserv', function($rootScope, i18nserv) {
  // initialization code (similar to main)
    /**
     * usage: {{_("i18n_string")}}
     */
    $rootScope._ = function(str) {
      return i18nserv.gettext(str, $rootScope.i18nLocale);
    };
  }]).

  factory('i18nserv', ['gettextData', function(gettextData) {
  // service: for translating texts according to locale

    var i18nStr = gettextData.all;

    function gettext(value, locale) {
      if (i18nStr.hasOwnProperty(locale)) {
        if (i18nStr[locale].hasOwnProperty(value)) {
          if (i18nStr[locale][value] !== '' &&
              i18nStr[locale][value] !== null)
            return i18nStr[locale][value];
        }
      }
      return value;
    }

    return { gettext: gettext };
  }]);
ngGettextData.js | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
angular.module('gettextData', []).
  factory('gettextData', [function() {
    var data = {
      "zh_TW": {
        "Home": "首頁",
        "Canon": "經典"
      },
      "vi_VN": {
        "Home": "Trang chính",
        "Canon": "Kinh điển"
      }
    }
    var serviceInstance = { all: data };
    return serviceInstance;
  }]);

Tested on: Chromium Version 50.0.2661.102 Ubuntu 16.04 (64-bit), AngularJS 1.5.5.


References:

[1]
[2][AngularJS] i18n Directive
[3][Golang] gettext Function on Frontend (Browser) by GopherJS