You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

263 lines
7.3 KiB

  1. ngStorage
  2. =========
  3. [![Build Status](https://travis-ci.org/gsklee/ngStorage.svg)](https://travis-ci.org/gsklee/ngStorage)
  4. [![Dependency Status](https://david-dm.org/gsklee/ngStorage.svg)](https://david-dm.org/gsklee/ngStorage)
  5. [![devDependency Status](https://david-dm.org/gsklee/ngStorage/dev-status.svg)](https://david-dm.org/gsklee/ngStorage#info=devDependencies)
  6. An [AngularJS](https://github.com/angular/angular.js) module that makes Web Storage working in the *Angular Way*. Contains two services: `$localStorage` and `$sessionStorage`.
  7. ### Differences with Other Implementations
  8. * **No Getter 'n' Setter Bullshit** - Right from AngularJS homepage: "Unlike other frameworks, there is no need to [...] wrap the model in accessors methods. Just plain old JavaScript here." Now you can enjoy the same benefit while achieving data persistence with Web Storage.
  9. * **sessionStorage** - We got this often-overlooked buddy covered.
  10. * **Cleanly-Authored Code** - Written in the *Angular Way*, well-structured with testability in mind.
  11. * **No Cookie Fallback** - With Web Storage being [readily available](http://caniuse.com/namevalue-storage) in [all the browsers AngularJS officially supports](http://docs.angularjs.org/misc/faq#canidownloadthesourcebuildandhosttheangularjsenvironmentlocally), such fallback is largely redundant.
  12. Install
  13. =======
  14. ### Bower
  15. ```bash
  16. bower install ngstorage
  17. ```
  18. *NOTE:* We are `ngstorage` and *NOT* `ngStorage`. The casing is important!
  19. ### NPM
  20. ```bash
  21. npm install ngstorage
  22. ```
  23. *NOTE:* We are `ngstorage` and *NOT* `ngStorage`. The casing is important!
  24. ### nuget
  25. ```bash
  26. Install-Package gsklee.ngStorage
  27. ```
  28. Or search for `Angular ngStorage` in the nuget package manager. <https://www.nuget.org/packages/gsklee.ngStorage>
  29. CDN
  30. ===
  31. ### cdnjs
  32. cdnjs now hosts ngStorage at <https://cdnjs.com/libraries/ngStorage>
  33. To use it
  34. ``` html
  35. <script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js"></script>
  36. ```
  37. ### jsDelivr
  38. jsDelivr hosts ngStorage at <http://www.jsdelivr.com/#!ngstorage>
  39. To use is
  40. ``` html
  41. <script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
  42. ```
  43. Usage
  44. =====
  45. ### Require ngStorage and Inject the Services
  46. ```javascript
  47. angular.module('app', [
  48. 'ngStorage'
  49. ]).controller('Ctrl', function(
  50. $scope,
  51. $localStorage,
  52. $sessionStorage
  53. ){});
  54. ```
  55. ### Read and Write | [Demo](http://plnkr.co/edit/3vfRkvG7R9DgQxtWbGHz?p=preview)
  56. Pass `$localStorage` (or `$sessionStorage`) by reference to a hook under `$scope` in plain ol' JavaScript:
  57. ```javascript
  58. $scope.$storage = $localStorage;
  59. ```
  60. And use it like you-already-know:
  61. ```html
  62. <body ng-controller="Ctrl">
  63. <button ng-click="$storage.counter = $storage.counter + 1">{{$storage.counter}}</button>
  64. </body>
  65. ```
  66. > Optionally, specify default values using the `$default()` method:
  67. >
  68. > ```javascript
  69. > $scope.$storage = $localStorage.$default({
  70. > counter: 42
  71. > });
  72. > ```
  73. With this setup, changes will be automatically sync'd between `$scope.$storage`, `$localStorage`, and localStorage - even across different browser tabs!
  74. ### Read and Write Alternative (Not Recommended) | [Demo](http://plnkr.co/edit/9ZmkzRkYzS3iZkG8J5IK?p=preview)
  75. If you're not fond of the presence of `$scope.$storage`, you can always use watchers:
  76. ```javascript
  77. $scope.counter = $localStorage.counter || 42;
  78. $scope.$watch('counter', function() {
  79. $localStorage.counter = $scope.counter;
  80. });
  81. $scope.$watch(function() {
  82. return angular.toJson($localStorage);
  83. }, function() {
  84. $scope.counter = $localStorage.counter;
  85. });
  86. ```
  87. This, however, is not the way ngStorage is designed to be used with. As can be easily seen by comparing the demos, this approach is way more verbose, and may have potential performance implications as the values being watched quickly grow.
  88. ### Delete | [Demo](http://plnkr.co/edit/o4w3VGqmp8opfrWzvsJy?p=preview)
  89. Plain ol' JavaScript again, what else could you better expect?
  90. ```javascript
  91. // Both will do
  92. delete $scope.$storage.counter;
  93. delete $localStorage.counter;
  94. ```
  95. This will delete the corresponding entry inside the Web Storage.
  96. ### Delete Everything | [Demo](http://plnkr.co/edit/YiG28KTFdkeFXskolZqs?p=preview)
  97. If you wish to clear the Storage in one go, use the `$reset()` method:
  98. ```javascript
  99. $localStorage.$reset();
  100. ````
  101. > Optionally, pass in an object you'd like the Storage to reset to:
  102. >
  103. > ```javascript
  104. > $localStorage.$reset({
  105. > counter: 42
  106. > });
  107. > ```
  108. ### Permitted Values | [Demo](http://plnkr.co/edit/n0acYLdhk3AeZmPOGY9Z?p=preview)
  109. You can store anything except those [not supported by JSON](http://www.json.org/js.html):
  110. * `Infinity`, `NaN` - Will be replaced with `null`.
  111. * `undefined`, Function - Will be removed.
  112. ### Usage from config phase
  113. To read and set values during the Angular config phase use the `.get/.set`
  114. functions provided by the provider.
  115. ```javascript
  116. var app = angular.module('app', ['ngStorage'])
  117. .config(['$localStorageProvider',
  118. function ($localStorageProvider) {
  119. $localStorageProvider.get('MyKey');
  120. $localStorageProvider.set('MyKey', { k: 'value' });
  121. }]);
  122. ```
  123. ### Prefix
  124. To change the prefix used by ngStorage use the provider function `setKeyPrefix`
  125. during the config phase.
  126. ```javascript
  127. var app = angular.module('app', ['ngStorage'])
  128. .config(['$localStorageProvider',
  129. function ($localStorageProvider) {
  130. $localStorageProvider.setKeyPrefix('NewPrefix');
  131. }])
  132. ```
  133. ### Custom serialization
  134. To change how ngStorage serializes and deserializes values (uses JSON by default) you can use your own functions.
  135. ```javascript
  136. angular.module('app', ['ngStorage'])
  137. .config(['$localStorageProvider',
  138. function ($localStorageProvider) {
  139. var mySerializer = function (value) {
  140. // Do what you want with the value.
  141. return value;
  142. };
  143. var myDeserializer = function (value) {
  144. return value;
  145. };
  146. $localStorageProvider.setSerializer(mySerializer);
  147. $localStorageProvider.setDeserializer(myDeserializer);
  148. }];)
  149. ```
  150. ### Minification
  151. Just run `$ npm install` to install dependencies. Then run `$ grunt` for minification.
  152. ### Hints
  153. #### Watch the watch
  154. ngStorage internally uses an Angular watch to monitor changes to the `$storage`/`$localStorage` objects. That means that a digest cycle is required to persist your new values into the browser local storage.
  155. Normally this is not a problem, but, for example, if you launch a new window after saving a value...
  156. ```javascript
  157. $scope.$storage.school = theSchool;
  158. $log.debug("launching " + url);
  159. var myWindow = $window.open("", "_self");
  160. myWindow.document.write(response.data);
  161. ```
  162. the new values will not reliably be saved into the browser local storage. Allow a digest cycle to occur by using a zero-value `$timeout` as:
  163. ```javascript
  164. $scope.$storage.school = theSchool;
  165. $log.debug("launching and saving the new value" + url);
  166. $timeout(function(){
  167. var myWindow = $window.open("", "_self");
  168. myWindow.document.write(response.data);
  169. });
  170. ```
  171. or better using `$scope.$evalAsync` as:
  172. ```javascript
  173. $scope.$storage.school = theSchool;
  174. $log.debug("launching and saving the new value" + url);
  175. $scope.$evalAsync(function(){
  176. var myWindow = $window.open("", "_self");
  177. myWindow.document.write(response.data);
  178. });
  179. ```
  180. And your new values will be persisted correctly.
  181. Todos
  182. =====
  183. * ngdoc Documentation
  184. * Namespace Support
  185. * Unit Tests
  186. * Grunt Tasks
  187. Any contribution will be appreciated.