Get Over Myself!

今日の自分を超えるための備忘録。

AngularJS の日本語対応 (angular-i18n)

AngularJS でcurrencyフィルタやdateフィルタの表示を日本語に合わせるには?

AngularJS のフィルタは便利な機能です。その中でcurrencyフィルタやdateフィルタといった、フォーマットを整えてくれるフィルタがありますが、デフォルトではUS表記になっています。これを日本語の表記に合わせるには、angular-i18n モジュールを利用します。

以下の方法は grunt-wiredep使用の環境でangular-i18nをbowerでインストールしたら注入できないとメッセージ - Qiita を参考にさせていただきました。

angular-i18n モジュールをインストールする

Bower を利用してインストールします。

$ bower i angular-i18n --save
bower not-cached    git://github.com/angular/bower-angular-i18n.git#*
bower resolve       git://github.com/angular/bower-angular-i18n.git#*
bower download      https://github.com/angular/bower-angular-i18n/archive/v1.2.24.tar.gz
bower extract       angular-i18n#* archive.tar.gz
bower invalid-meta  angular-i18n is missing "main" entry in bower.json
bower resolved      git://github.com/angular/bower-angular-i18n.git#1.2.24
bower install       angular-i18n#1.2.24

ん? bower invalid-meta angular-i18n is missing "main" entry in bower.jsonという警告が出ていますね。 同時にgulp serveなどを走らせていた場合、以下のような警告が出てしまいます。

angular-i18n was not injected in your file.
Please go take a look in "app/bower_components/angular-i18n" for the file you need, the manually include it in your file.

Bower が angular-i18n モジュールのうち、どのファイルをインクルードしていいのかわからないようです。

angular-i18n の main を指定する

bower.jsonで明示的に使用するロケールファイルを指定してあげましょう。

// bower.json
{
  "name": "myApp",
  "version": "0.0.0",
  ... 省略 ....
  "resolutions": {
    "angular": "1.3.x",
    "jquery": "2.x.x"
  },
  // ここから追記
  "overrides": {
    "angular-i18n": {
      "main": "angular-locale_ja-jp.js"
    }
  }
  // ここまで追記
}

これでindex.htmlに自動的に追記されるようになります。

<!-- index.html の抜粋 -->
<!-- bower:js -->
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-i18n/angular-locale_ja-jp.js"></script>
<!-- endbower -->

日本語表記に変わったか確かめてみる

index.html

<!DOCTYPE html>
<html lang="ja" ng-app="app">
<head>
  <meta charset="UTF-8">
  <title>Format test</title>
</head>
<body>
  <div ng-controller="FormatCtrl">
    <h1>日付</h1>
    <p>{{today}}</p>
    <p>{{today | date: 'fullDate'}}</p>

    <h1>通貨</h1>
    <p>{{yen}}</p>
    <p>{{yen | currency}}</p>
  </div>

    <!-- bower:js -->
    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-i18n/angular-locale_ja-jp.js"></script>
    <!-- endbower -->

    <script src="scripts/main.js"></script>
</body>
</html>

main.js

(function() { 'use strict'; 
angular.module('app', []).controller('FormatCtrl', ['$scope', function($scope) {
  $scope.today = new Date();
  $scope.yen = 1000000;
}]);
})();

結果

日付

"2014-09-15T11:38:50.158Z"

2014年9月15日月曜日

通貨

1000000

\1,000,000

きちんと日本語用にフォーマットされていますね。