AngularJS で cookie を扱う術

AngularJS で cookie を扱う術を調べてみたのでメモ

ngCookies

angular公式のライブラリ。以下のコマンドでbowerからインストールできる。

bower install angular-cookies --save

追加、削除、読み込みの簡単なインターフェイスを提供してくれる。こんなかんじ

angular.module('cookieExample', ['ngCookies'])
.controller('ExampleController', ['$cookieStore', function($cookieStore) {
  $cookieStore.put('name','kitak');

  var name = $cookieStore.get('name');

  $cookieStore.remove('name');
}]);

domainとかpathの指定はできない。

ivpusic/angular-cookie

domainとかpathの指定もしたい場合は、ivpusic/angular-cookie · GitHub がよいかも。jquery.cookie.jsのようなインターフェイスを提供してくれる。

angular.module('cookieExample', ['ngCookies'])
.controller('ExampleController', ['ipCookie', function(ipCookie) {
  ipCookie('name', 'kitak', { path: '/some/path', expires: 12 });

  ipCookie.remove('name', { path: '/some/path' });
}]);