diff --git a/ngStorage.js b/ngStorage.js index 0d71a2d..7bd7211 100644 --- a/ngStorage.js +++ b/ngStorage.js @@ -1,13 +1,22 @@ -'use strict'; +(function(angular, factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + define('ngStore', ['angular'], function(angular) { + return factory(angular); + }); + } else { + return factory(angular); + } +}(typeof angular === 'undefined' ? null : angular, function(angular) { -(function() { + 'use strict'; /** * @ngdoc overview * @name ngStorage */ - angular.module('ngStorage', []). + angular.module('ngStorage', []) /** * @ngdoc object @@ -16,7 +25,7 @@ * @requires $window */ - factory('$localStorage', _storageFactory('localStorage')). + .factory('$localStorage', _storageFactory('localStorage')) /** * @ngdoc object @@ -25,21 +34,23 @@ * @requires $window */ - factory('$sessionStorage', _storageFactory('sessionStorage')); + .factory('$sessionStorage', _storageFactory('sessionStorage')); function _storageFactory(storageType) { return [ '$rootScope', '$window', '$log', + '$timeout', function( $rootScope, $window, - $log + $log, + $timeout ){ // #9: Assign a placeholder object if Web Storage is unavailable to prevent breaking the entire AngularJS app - var webStorage = $window[storageType] || ($log.warn('This browser does not support Web Storage!'), {}), + var webStorage, $storage = { $default: function(items) { for (var k in items) { @@ -59,7 +70,15 @@ _last$storage, _debounce; - for (var i = 0, k; i < webStorage.length; i++) { + try { + webStorage = $window[storageType]; + webStorage.length; + } catch(e) { + $log.warn('This browser does not support Web Storage!'); + webStorage = {}; + } + + for (var i = 0, l = webStorage.length, k; i < l; i++) { // #8, #10: `webStorage.key(i)` may be an empty string (or throw an exception in IE9 if `webStorage` is empty) (k = webStorage.key(i)) && 'ngStorage-' === k.slice(0, 10) && ($storage[k.slice(10)] = angular.fromJson(webStorage.getItem(k))); } @@ -67,7 +86,7 @@ _last$storage = angular.copy($storage); $rootScope.$watch(function() { - _debounce || (_debounce = setTimeout(function() { + _debounce || (_debounce = $timeout(function() { _debounce = null; if (!angular.equals($storage, _last$storage)) { @@ -83,7 +102,7 @@ _last$storage = angular.copy($storage); } - }, 100)); + }, 100, false)); }); // #6: Use `$window.addEventListener` instead of `angular.element` to avoid the jQuery-specific `event.originalEvent` @@ -102,4 +121,4 @@ ]; } -})(); +}));