42
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AngularJSでlocalStorageを使う

Last updated at Posted at 2014-08-04

ANGULAR MODULESlocalStorageで検索すると、最も使っている人が多い ngStorage を使ってみました。READMEの通りですが、メモっておきます。

  • Install
$ bower install ngstorage
  • moduleにngStorageへの依存を貼ります
module
var app = angular.module('starter.controllers', ['ngStorage'])
  • controllerにサービスを読み込む
    SessionStorageなら$sessionStorage
    LoalStorageなら$localStorage

  • localStorageを読み込む
    例えば、isEnableHogeとpositionXHogeを読み込む場合。

Load
$scope.$storage = $localStorage.$default({
            isEnableHoge: false,
   			 positionXHoge: 10
});

default()で設定しておけば、localStorageに実データがない場合はデフォルト値を使い、存在する場合はその値を使う。(helpには説明が書いてないけど、私の試した範囲だとそうなりました。)default()は使った方がいいと思います。

  • localStorageへの保存
Save
       $scope.$storage.isEnableHoge = true; 
       $scope.$storage.positionXHoge = 34;

簡単です。
最後にionicと組み合わせるとこんな感じでLoadすれば、アプリケーションの設定データとして使えます。

var app = angular.module('hoge', ['ngStorage'])

app.controller('AppCtrl', function($scope, $ionicPlatform
  $ionicPlatform.ready(function() {
		$scope.$storage = $localStorage.$default({
            isEnableHoge: false,
            positionXHoge: 10
	});
));
42
41
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?