Compare commits

..

No commits in common. 'master' and '0.1.0' have entirely different histories.

1
.gitignore vendored

@ -5,4 +5,3 @@ bower_components
npm-debug.log
*.swp
.idea
coverage

@ -5,5 +5,4 @@ before_script:
- 'npm install -g grunt-cli'
- 'npm install -g bower'
- 'bower install'
script: grunt test
after_script: "npm install coveralls@2.10.0 && cat ./coverage/*/lcov.info | coveralls"
script: grunt test

@ -1,8 +0,0 @@
<a name="0.1.1"></a>
# 0.1.1 (2014-10-06)
## Breaking Changes
- update your `index.html` file to reference angular-local-storage at its new
path inside the `dist` directory `/angular-local-storage/dist/angular-local-storage.js`

@ -30,7 +30,7 @@ module.exports = function(grunt) {
footer: '})( window, window.angular );'
},
dist: {
src: ['src/common.js', 'src/angular-local-storage.js'],
src: ['src/*.js'],
dest: '<%= dirs.dest %>/<%= pkg.name %>.js'
}
},
@ -46,7 +46,12 @@ module.exports = function(grunt) {
karma: {
options: {
autowatch: true,
configFile: 'test/karma.conf.js'
browsers: [
'PhantomJS'
],
configFile: 'test/karma.conf.js',
reporters: ['dots'],
singleRun: true
},
unit: {}
},

@ -1,8 +1,8 @@
Angular Local Storage
Copyright 2015 Gregory Pike
Copyright 2013 Gregory Pike
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -1,378 +1,60 @@
angular-local-storage
=====================
**Note to myself: Used for an other project, do not delete.**
An Angular module that gives you access to the browsers local storage, **v0.1.5**
An Angular module that gives you access to the browsers local storage
[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Dependency Status][david-image]][david-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![Build Status](https://secure.travis-ci.org/grevory/angular-local-storage.png?branch=master)](https://travis-ci.org/grevory/)
##Table of contents:
- [Get Started](#get-started)
- [Development](#development)
- [Configuration](#configuration)
- [setPrefix](#setprefix)
- [setStorageType](#setstoragetype)
- [setStorageCookie](#setstoragecookie)
- [setStorageCookieDomain](#setstoragecookiedomain)
- [setNotify](#setnotify)
- [Example](#configuration-example)
- [API Documentation](#api-documentation)
- [isSupported](#issupported)
- [getStorageType](#getstoragetype)
- [set](#set)
- [get](#get)
- [keys](#keys)
- [remove](#remove)
- [clearAll](#clearall)
- [bind](#bind)
- [deriveKey](#derivekey)
- [length](#length)
- [cookie](#cookie)
- [isSupported](#cookieissupported)
- [set](#cookieset)
- [get](#cookieget)
- [remove](#cookieremove)
- [clearAll](#cookieclearall)
Installation:
##Get Started
**(1)** You can install angular-local-storage using 2 different ways:<br/>
**Git:**
clone & build [this](https://github.com/grevory/angular-local-storage.git) repository<br/>
**Bower:**
```bash
$ bower install angular-local-storage
bower install angular-local-storage
```
**npm:**
```bash
$ npm install angular-local-storage
```
**(2)** Include `angular-local-storage.js` (or `angular-local-storage.min.js`) in your `index.html`, after including Angular itself.
**(3)** Add `'LocalStorageModule'` to your main module's list of dependencies.
Example use:
When you're done, your setup should look similar to the following:
```javascript
angular.module('yourModule', ['LocalStorageModule'])
.controller('yourCtrl', [
'$scope',
'localStorageService',
function($scope, localStorageService) {
// Start fresh
localStorageService.clearAll();
```html
<!doctype html>
<html ng-app="myApp">
<head>
</head>
<body>
...
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
<script src="bower_components/js/angular-local-storage.min.js"></script>
...
<script>
var myApp = angular.module('myApp', ['LocalStorageModule']);
</script>
...
</body>
</html>
```
##Configuration
###setPrefix
You could set a prefix to avoid overwriting any local storage variables from the rest of your app<br/>
**Default prefix:** `ls.<your-key>`
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('yourAppName');
});
```
###setStorageType
You could change web storage type to localStorage or sessionStorage<br/>
**Default storage:** `localStorage`
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setStorageType('sessionStorage');
});
```
###setStorageCookie
Set cookie options (usually in case of fallback)<br/>
**expiry:** number of days before cookies expire (0 = does not expire). **default:** `30`<br/>
**path:** the web path the cookie represents. **default:** `'/'`
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setStorageCookie(45, '<path>');
});
```
###setStorageCookieDomain
Set the cookie domain, since this runs inside a the `config()` block, only providers and constants can be injected. As a result, `$location` service can't be used here, use a hardcoded string or `window.location`.<br/>
**No default value**
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setStorageCookieDomain('<domain>');
});
```
// Set a key
localStorageService.set('Favorite Sport','Ultimate Frisbee');
For local testing (when you are testing on localhost) set the domain to an empty string ''. Setting the domain to 'localhost' will not work on all browsers (eg. Chrome) since some browsers only allow you to set domain cookies for registry controlled domains, i.e. something ending in .com or so, but not IPs **or intranet hostnames** like localhost. </br>
// Delete a key
localStorageService.remove('Favorite Sport');
}]);
###setNotify
Send signals for each of the following actions:<br/>
**setItem** , default: `true`<br/>
**removeItem** , default: `false`
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setNotify(true, true);
});
```
###Configuration Example
Using all together
```js
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('myApp')
.setStorageType('sessionStorage')
.setNotify(true, true)
});
```
##API Documentation
##isSupported
Checks if the browser support the current storage type(e.g: `localStorage`, `sessionStorage`).
**Returns:** `Boolean`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
if(localStorageService.isSupported) {
//...
}
//...
});
```
###getStorageType
**Returns:** `String`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
var storageType = localStorageService.getStorageType(); //e.g localStorage
//...
});
```
###set
Directly adds a value to local storage.<br/>
If local storage is not supported, use cookies instead.<br/>
**Returns:** `Boolean`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function submit(key, val) {
return localStorageService.set(key, val);
}
//...
});
```
###get
Directly get a value from local storage.<br/>
If local storage is not supported, use cookies instead.<br/>
**Returns:** `value from local storage`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function getItem(key) {
return localStorageService.get(key);
}
//...
});
```
###keys
Return array of keys for local storage, ignore keys that not owned.<br/>
**Returns:** `value from local storage`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
var lsKeys = localStorageService.keys();
//...
});
```
###remove
Remove an item from local storage by key.<br/>
If local storage is not supported, use cookies instead.<br/>
**Returns:** `Boolean`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function removeItem(key) {
return localStorageService.remove(key);
}
//...
});
```
###clearAll
Remove all data for this app from local storage.<br/>
If local storage is not supported, use cookies instead.<br/>
**Note:** Optionally takes a regular expression string and removes matching.<br/>
**Returns:** `Boolean`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function clearNumbers(key) {
return localStorageService.clearAll(/^\d+$/);
}
//...
function clearAll() {
return localStorageService.clearAll();
}
});
```
###bind
Bind $scope key to localStorageService.
**Usage:** `localStorageService.bind(scope, property, value[optional], key[optional])`
***key:*** The corresponding key used in local storage
**Returns:** deregistration function for this listener.
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
localStorageService.set('property', 'oldValue');
$scope.unbind = localStorageService.bind($scope, 'property');
//Test Changes
$scope.update = function(val) {
$scope.property = val;
$timeout(function() {
alert("localStorage value: " + localStorageService.get('property'));
});
}
//...
});
```
```html
<div ng-controller="MainCtrl">
<p>{{property}}</p>
<input type="text" ng-model="lsValue"/>
<button ng-click="update(lsValue)">update</button>
<button ng-click="unbind()">unbind</button>
</div>
/*
To set the prefix of your localStorage name, you can use the setPrefix method
available on the localStorageServiceProvider
*/
angular.module('yourModule', ['LocalStorageModule'])
.config(['localStorageServiceProvider', function(localStorageServiceProvider){
localStorageServiceProvider.setPrefix('newPrefix');
}]);
```
###deriveKey
Return the derive key
**Returns** `String`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
localStorageService.set('property', 'oldValue');
//Test Result
console.log(localStorageService.deriveKey('property')); // ls.property
//...
});
```
###length
Return localStorageService.length, ignore keys that not owned.
**Returns** `Number`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
var lsLength = localStorageService.length(); // e.g: 7
//...
});
```
##Cookie
Deal with browser's cookies directly.
##cookie.isSupported
Checks if cookies are enabled in the browser.
**Returns:** `Boolean`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
if(localStorageService.cookie.isSupported) {
//...
}
//...
});
```
###cookie.set
Directly adds a value to cookies.<br/>
**Note:** Typically used as a fallback if local storage is not supported.<br/>
**Returns:** `Boolean`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function submit(key, val) {
return localStorageService.cookie.set(key, val);
}
//...
});
```
###cookie.get
Directly get a value from a cookie.<br/>
**Returns:** `value from local storage`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function getItem(key) {
return localStorageService.cookie.get(key);
}
//...
});
```
###cookie.remove
Remove directly value from a cookie.<br/>
**Returns:** `Boolean`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function removeItem(key) {
return localStorageService.cookie.remove(key);
}
//...
});
```
###cookie.clearAll
Remove all data for this app from cookie.<br/>
**Returns:** `Boolean`
```js
myApp.controller('MainCtrl', function($scope, localStorageService) {
//...
function clearAll() {
return localStorageService.cookie.clearAll();
}
});
#### How to bind to a $scope variable:
Usage: localStorageService.bind(scope, scopeKey, def, lsKey);
```
// Example
$scope.anArtist = {'firstname':'Pablo', 'lastname':'Picasso'};
Check out the full demo at http://gregpike.net/demos/angular-local-storage/demo.html
// Bind to local storage service
localStorageService.bind($scope, 'anArtist', $scope.anArtist, 'specialArtist');
##Development:
* Don't forget about tests.
* If you planning add some feature please create issue before.
Clone the project:
```sh
$ git clone https://github.com/<your-repo>/angular-local-storage.git
$ npm install
$ bower install
```
Run the tests:
```sh
$ grunt test
```
**Deploy:**<br/>
Run the build task, update version before(bower,package)
```sh
$ grunt dist
$ git tag 0.*.*
$ git push origin master --tags
// get bound data:
console.log(localStorageService.get('specialArtist'));
```
[npm-image]: https://img.shields.io/npm/v/angular-local-storage.svg?style=flat-square
[npm-url]: https://npmjs.org/package/angular-local-storage
[travis-image]: https://img.shields.io/travis/grevory/angular-local-storage.svg?style=flat-square
[travis-url]: https://travis-ci.org/grevory/angular-local-storage
[coveralls-image]: https://img.shields.io/coveralls/grevory/angular-local-storage.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/grevory/angular-local-storage
[david-image]: http://img.shields.io/david/grevory/angular-local-storage.svg?style=flat-square
[david-url]: https://david-dm.org/grevory/angular-local-storage
[license-image]: http://img.shields.io/npm/l/angular-local-storage.svg?style=flat-square
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/angular-local-storage.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/angular-local-storage
Check out the full demo and documentation at http://gregpike.net/demos/angular-local-storage/demo.html
To do:
- Add tests
- Expand Readme

@ -1,6 +1,6 @@
{
"name": "angular-local-storage",
"version": "0.1.5",
"version": "0.1.0",
"homepage": "http://gregpike.net/demos/angular-local-storage/demo.html",
"authors": [
"grevory <greg@gregpike.ca>"

@ -1,13 +1,13 @@
'use strict';
window.angular.module('demoModule', ['LocalStorageModule'])
.config(function(localStorageServiceProvider){
angular.module('demoModule', ['LocalStorageModule'])
.config(['localStorageServiceProvider', function(localStorageServiceProvider){
localStorageServiceProvider.setPrefix('demoPrefix');
// localStorageServiceProvider.setStorageCookieDomain('example.com');
// localStorageServiceProvider.setStorageType('sessionStorage');
})
.controller('DemoCtrl',
}])
.controller('DemoCtrl', [
'$scope',
'localStorageService',
function($scope, localStorageService) {
$scope.localStorageDemo = localStorageService.get('localStorageDemo');
$scope.$watch('localStorageDemo', function(value){
localStorageService.set('localStorageDemo',value);
@ -23,13 +23,5 @@ window.angular.module('demoModule', ['LocalStorageModule'])
if (!localStorageService.isSupported) {
$scope.storageType = 'Cookie';
}
$scope.$watch(function(){
return localStorageService.get('localStorageDemo');
}, function(value){
$scope.localStorageDemo = value;
});
$scope.clearAll = localStorageService.clearAll;
}
);
]);

@ -1,17 +1,18 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Demo of Angular Local Storage Module</title>
<meta name="description" content="Demo of Angular Local Storage Module">
<meta name="author" content="Gregory Pike">
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root of your domain and delete these references -->
<!--[if IE]><![endif]--><!-- Used to speed CSS loading -->
<link rel="stylesheet" href="http://necolas.github.com/normalize.css/2.0.1/normalize.css">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" rel="stylesheet">
<link href="demo-style.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
@ -29,18 +30,16 @@
</div>
<div class="hero-unit">
<h1>Give it a try</h1>
<div ng-controller="DemoCtrl">
<p><input type="text" ng-model="localStorageDemo" placeholder="Start typing..."></p>
<blockquote class="well" ng-show="localStorageDemoValue">
<p ng-bind="localStorageDemoValue"></p>
<p>{{localStorageDemoValue}}</p>
<small>{{storageType}} value</small>
</blockquote>
<p><button ng-click="clearAll()">Clear All</button></p>
</div>
<p>The Angular Local Storage Module is meant to be a plug-and-play Angular module for accessing the browsers Local Storage API.</p>
@ -145,11 +144,11 @@ var YourCtrl = function($scope, localStorageService, ...) {
</div>
<!-- END DEMO -->
<!-- JAVASCRIPT -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"></script>
<script src="https://rawgit.com/grevory/angular-local-storage/master/dist/angular-local-storage.min.js"></script>
<script src="../dist/angular-local-storage.min.js"></script>
<script src="demo-app.js"></script>
</body>
</html>

@ -1,36 +1,18 @@
/**
* An Angular module that gives you access to the browsers local storage
* @version v0.1.5 - 2015-01-22
* @version v0.0.8 - 2014-08-15
* @link https://github.com/grevory/angular-local-storage
* @author grevory <greg@gregpike.ca>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function ( window, angular, undefined ) {
/*jshint globalstrict:true*/
'use strict';
var isDefined = angular.isDefined,
isUndefined = angular.isUndefined,
isNumber = angular.isNumber,
isObject = angular.isObject,
isArray = angular.isArray,
extend = angular.extend,
toJson = angular.toJson,
fromJson = angular.fromJson;
// Test if string is only contains numbers
// e.g '1' => true, "'1'" => true
function isStringNumber(num) {
return /^-?\d+\.?\d*$/.test(num.replace(/["']/g, ''));
}
var angularLocalStorage = angular.module('LocalStorageModule', []);
angularLocalStorage.provider('localStorageService', function() {
// You should set a prefix to avoid overwriting any local storage variables from the rest of your app
// e.g. localStorageServiceProvider.setPrefix('yourAppName');
// e.g. localStorageServiceProvider.setPrefix('youAppName');
// With provider you can use config as this:
// myApp.config(function (localStorageServiceProvider) {
// localStorageServiceProvider.prefix = 'yourAppName';
@ -57,13 +39,11 @@ angularLocalStorage.provider('localStorageService', function() {
// Setter for the prefix
this.setPrefix = function(prefix) {
this.prefix = prefix;
return this;
};
// Setter for the storageType
this.setStorageType = function(storageType) {
this.storageType = storageType;
return this;
this.storageType = storageType;
};
// Setter for cookie config
@ -72,13 +52,11 @@ angularLocalStorage.provider('localStorageService', function() {
expiry: exp,
path: path
};
return this;
};
// Setter for cookie domain
this.setStorageCookieDomain = function(domain) {
this.cookie.domain = domain;
return this;
};
// Setter for notification config
@ -88,10 +66,11 @@ angularLocalStorage.provider('localStorageService', function() {
setItem: itemSet,
removeItem: itemRemove
};
return this;
};
this.$get = ['$rootScope', '$window', '$document', '$parse', function($rootScope, $window, $document, $parse) {
this.$get = ['$rootScope', '$window', '$document', function($rootScope, $window, $document) {
var self = this;
var prefix = self.prefix;
var cookie = self.cookie;
@ -112,7 +91,7 @@ angularLocalStorage.provider('localStorageService', function() {
}
var deriveQualifiedKey = function(key) {
return prefix + key;
};
}
// Checks the browser to see if local storage is supported
var browserSupportsLocalStorage = (function () {
try {
@ -144,28 +123,24 @@ angularLocalStorage.provider('localStorageService', function() {
// If local storage is not available in the browser use cookies
// Example use: localStorageService.add('library','angular');
var addToLocalStorage = function (key, value) {
// Let's convert undefined values to null to get the value consistent
if (isUndefined(value)) {
value = null;
} else if (isObject(value) || isArray(value) || isNumber(+value || value)) {
value = toJson(value);
}
// If this browser does not support local storage use cookies
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
}
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
if (notify.setItem) {
$rootScope.$broadcast('LocalStorageModule.notification.setitem', {key: key, newvalue: value, storageType: 'cookie'});
}
return addToCookies(key, value);
}
// Let's convert undefined values to null to get the value consistent
if (typeof value === "undefined") {
value = null;
}
try {
if (isObject(value) || isArray(value)) {
value = toJson(value);
if (angular.isObject(value) || angular.isArray(value)) {
value = angular.toJson(value);
}
if (webStorage) {webStorage.setItem(deriveQualifiedKey(key), value)};
if (notify.setItem) {
@ -183,10 +158,7 @@ angularLocalStorage.provider('localStorageService', function() {
var getFromLocalStorage = function (key) {
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
}
$rootScope.$broadcast('LocalStorageModule.notification.warning','LOCAL_STORAGE_NOT_SUPPORTED');
return getFromCookies(key);
}
@ -197,8 +169,8 @@ angularLocalStorage.provider('localStorageService', function() {
return null;
}
if (item.charAt(0) === "{" || item.charAt(0) === "[" || isStringNumber(item)) {
return fromJson(item);
if (item.charAt(0) === "{" || item.charAt(0) === "[") {
return angular.fromJson(item);
}
return item;
@ -207,11 +179,8 @@ angularLocalStorage.provider('localStorageService', function() {
// Remove an item from local storage
// Example use: localStorageService.remove('library'); // removes the key/value pair of library='angular'
var removeFromLocalStorage = function (key) {
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
}
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
if (notify.removeItem) {
$rootScope.$broadcast('LocalStorageModule.notification.removeitem', {key: key, storageType: 'cookie'});
}
@ -266,11 +235,8 @@ angularLocalStorage.provider('localStorageService', function() {
var tempPrefix = prefix.slice(0, -1);
var testRegex = new RegExp(tempPrefix + '.' + regularExpression);
if (!browserSupportsLocalStorage || self.storageType === 'cookie') {
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
}
if (!browserSupportsLocalStorage) {
$rootScope.$broadcast('LocalStorageModule.notification.warning', 'LOCAL_STORAGE_NOT_SUPPORTED');
return clearAllFromCookies();
}
@ -291,29 +257,27 @@ angularLocalStorage.provider('localStorageService', function() {
};
// Checks the browser to see if cookies are supported
var browserSupportsCookies = (function() {
var browserSupportsCookies = function() {
try {
return $window.navigator.cookieEnabled ||
return navigator.cookieEnabled ||
("cookie" in $document && ($document.cookie.length > 0 ||
($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false;
}
}());
};
// Directly adds a value to cookies
// Typically used as a fallback is local storage is not available in the browser
// Example use: localStorageService.cookie.add('library','angular');
var addToCookies = function (key, value) {
if (isUndefined(value)) {
if (typeof value === "undefined") {
return false;
} else if(isArray(value) || isObject(value)) {
value = toJson(value);
}
if (!browserSupportsCookies) {
if (!browserSupportsCookies()) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false;
}
@ -349,7 +313,7 @@ angularLocalStorage.provider('localStorageService', function() {
// Directly get a value from a cookie
// Example use: localStorageService.cookie.get('library'); // returns 'angular'
var getFromCookies = function (key) {
if (!browserSupportsCookies) {
if (!browserSupportsCookies()) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false;
}
@ -361,13 +325,7 @@ angularLocalStorage.provider('localStorageService', function() {
thisCookie = thisCookie.substring(1,thisCookie.length);
}
if (thisCookie.indexOf(deriveQualifiedKey(key) + '=') === 0) {
var storedValues = decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length))
try{
var obj = JSON.parse(storedValues);
return fromJson(obj)
}catch(e){
return storedValues
}
return decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length));
}
}
return null;
@ -397,43 +355,26 @@ angularLocalStorage.provider('localStorageService', function() {
return storageType;
};
// Add a listener on scope variable to save its changes to local storage
// Return a function which when called cancels binding
var bindToScope = function(scope, key, def, lsKey) {
lsKey = lsKey || key;
var value = getFromLocalStorage(lsKey);
var bindToScope = function(scope, key, def) {
var value = getFromLocalStorage(key);
if (value === null && isDefined(def)) {
if (value === null && angular.isDefined(def)) {
value = def;
} else if (isObject(value) && isObject(def)) {
value = extend(def, value);
} else if (angular.isObject(value) && angular.isObject(def)) {
value = angular.extend(def, value);
}
$parse(key).assign(scope, value);
scope[key] = value;
return scope.$watch(key, function(newVal) {
addToLocalStorage(lsKey, newVal);
}, isObject(scope[key]));
};
// Return localStorageService.length
// ignore keys that not owned
var lengthOfLocalStorage = function() {
var count = 0;
var storage = $window[storageType];
for(var i = 0; i < storage.length; i++) {
if(storage.key(i).indexOf(prefix) === 0 ) {
count++;
}
}
return count;
scope.$watchCollection(key, function(newVal) {
addToLocalStorage(key, newVal);
});
};
return {
isSupported: browserSupportsLocalStorage,
getStorageType: getStorageType,
set: addToLocalStorage,
put: addToLocalStorage,
add: addToLocalStorage, //DEPRECATED
get: getFromLocalStorage,
keys: getKeysForLocalStorage,
@ -441,9 +382,7 @@ angularLocalStorage.provider('localStorageService', function() {
clearAll: clearAllFromLocalStorage,
bind: bindToScope,
deriveKey: deriveQualifiedKey,
length: lengthOfLocalStorage,
cookie: {
isSupported: browserSupportsCookies,
set: addToCookies,
add: addToCookies, //DEPRECATED
get: getFromCookies,

@ -1,7 +1,7 @@
/**
* An Angular module that gives you access to the browsers local storage
* @version v0.1.5 - 2015-01-22
* @version v0.0.8 - 2014-08-15
* @link https://github.com/grevory/angular-local-storage
* @author grevory <greg@gregpike.ca>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/!function(a,b){"use strict";function c(a){return/^-?\d+\.?\d*$/.test(a.replace(/["']/g,""))}var d=b.isDefined,e=b.isUndefined,f=b.isNumber,g=b.isObject,h=b.isArray,i=b.extend,j=b.toJson,k=b.fromJson,l=b.module("LocalStorageModule",[]);l.provider("localStorageService",function(){this.prefix="ls",this.storageType="localStorage",this.cookie={expiry:30,path:"/"},this.notify={setItem:!0,removeItem:!1},this.setPrefix=function(a){return this.prefix=a,this},this.setStorageType=function(a){return this.storageType=a,this},this.setStorageCookie=function(a,b){return this.cookie={expiry:a,path:b},this},this.setStorageCookieDomain=function(a){return this.cookie.domain=a,this},this.setNotify=function(a,b){return this.notify={setItem:a,removeItem:b},this},this.$get=["$rootScope","$window","$document","$parse",function(a,b,l,m){var n,o=this,p=o.prefix,q=o.cookie,r=o.notify,s=o.storageType;l?l[0]&&(l=l[0]):l=document,"."!==p.substr(-1)&&(p=p?p+".":"");var t=function(a){return p+a},u=function(){try{var c=s in b&&null!==b[s],d=t("__"+Math.round(1e7*Math.random()));return c&&(n=b[s],n.setItem(d,""),n.removeItem(d)),c}catch(e){return s="cookie",a.$broadcast("LocalStorageModule.notification.error",e.message),!1}}(),v=function(b,c){if(e(c)?c=null:(g(c)||h(c)||f(+c||c))&&(c=j(c)),!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:"cookie"}),B(b,c);try{(g(c)||h(c))&&(c=j(c)),n&&n.setItem(t(b),c),r.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:b,newvalue:c,storageType:o.storageType})}catch(d){return a.$broadcast("LocalStorageModule.notification.error",d.message),B(b,c)}return!0},w=function(b){if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),C(b);var d=n?n.getItem(t(b)):null;return d&&"null"!==d?"{"===d.charAt(0)||"["===d.charAt(0)||c(d)?k(d):d:null},x=function(b){if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),r.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:"cookie"}),D(b);try{n.removeItem(t(b)),r.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:o.storageType})}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),D(b)}return!0},y=function(){if(!u)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),!1;var b=p.length,c=[];for(var d in n)if(d.substr(0,b)===p)try{c.push(d.substr(b))}catch(e){return a.$broadcast("LocalStorageModule.notification.error",e.Description),[]}return c},z=function(b){b=b||"";var c=p.slice(0,-1),d=new RegExp(c+"."+b);if(!u||"cookie"===o.storageType)return u||a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),E();var e=p.length;for(var f in n)if(d.test(f))try{x(f.substr(e))}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.message),E()}return!0},A=function(){try{return b.navigator.cookieEnabled||"cookie"in l&&(l.cookie.length>0||(l.cookie="test").indexOf.call(l.cookie,"test")>-1)}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),!1}}(),B=function(b,c){if(e(c))return!1;if((h(c)||g(c))&&(c=j(c)),!A)return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;try{var d="",f=new Date,i="";if(null===c?(f.setTime(f.getTime()+-864e5),d="; expires="+f.toGMTString(),c=""):0!==q.expiry&&(f.setTime(f.getTime()+24*q.expiry*60*60*1e3),d="; expires="+f.toGMTString()),b){var k="; path="+q.path;q.domain&&(i="; domain="+q.domain),l.cookie=t(b)+"="+encodeURIComponent(c)+d+k+i}}catch(m){return a.$broadcast("LocalStorageModule.notification.error",m.message),!1}return!0},C=function(b){if(!A)return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;for(var c=l.cookie&&l.cookie.split(";")||[],d=0;d<c.length;d++){for(var e=c[d];" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(t(b)+"=")){var f=decodeURIComponent(e.substring(p.length+b.length+1,e.length));try{var g=JSON.parse(f);return k(g)}catch(h){return f}}}return null},D=function(a){B(a,null)},E=function(){for(var a=null,b=p.length,c=l.cookie.split(";"),d=0;d<c.length;d++){for(a=c[d];" "===a.charAt(0);)a=a.substring(1,a.length);var e=a.substring(b,a.indexOf("="));D(e)}},F=function(){return s},G=function(a,b,c,e){e=e||b;var f=w(e);return null===f&&d(c)?f=c:g(f)&&g(c)&&(f=i(c,f)),m(b).assign(a,f),a.$watch(b,function(a){v(e,a)},g(a[b]))},H=function(){for(var a=0,c=b[s],d=0;d<c.length;d++)0===c.key(d).indexOf(p)&&a++;return a};return{isSupported:u,getStorageType:F,set:v,put:v,add:v,get:w,keys:y,remove:x,clearAll:z,bind:G,deriveKey:t,length:H,cookie:{isSupported:A,set:B,add:B,get:C,remove:D,clearAll:E}}}]})}(window,window.angular);
*/!function(a,b){"use strict";var c=b.module("LocalStorageModule",[]);c.provider("localStorageService",function(){this.prefix="ls",this.storageType="localStorage",this.cookie={expiry:30,path:"/"},this.notify={setItem:!0,removeItem:!1},this.setPrefix=function(a){this.prefix=a},this.setStorageType=function(a){this.storageType=a},this.setStorageCookie=function(a,b){this.cookie={expiry:a,path:b}},this.setStorageCookieDomain=function(a){this.cookie.domain=a},this.setNotify=function(a,b){this.notify={setItem:a,removeItem:b}},this.$get=["$rootScope","$window","$document",function(a,c,d){var e,f=this,g=f.prefix,h=f.cookie,i=f.notify,j=f.storageType;d?d[0]&&(d=d[0]):d=document,"."!==g.substr(-1)&&(g=g?g+".":"");var k=function(a){return g+a},l=function(){try{var b=j in c&&null!==c[j],d=k("__"+Math.round(1e7*Math.random()));return b&&(e=c[j],e.setItem(d,""),e.removeItem(d)),b}catch(f){return j="cookie",a.$broadcast("LocalStorageModule.notification.error",f.message),!1}}(),m=function(c,d){if(!l||"cookie"===f.storageType)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),i.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:c,newvalue:d,storageType:"cookie"}),s(c,d);"undefined"==typeof d&&(d=null);try{(b.isObject(d)||b.isArray(d))&&(d=b.toJson(d)),e&&e.setItem(k(c),d),i.setItem&&a.$broadcast("LocalStorageModule.notification.setitem",{key:c,newvalue:d,storageType:f.storageType})}catch(g){return a.$broadcast("LocalStorageModule.notification.error",g.message),s(c,d)}return!0},n=function(c){if(!l||"cookie"===f.storageType)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),t(c);var d=e?e.getItem(k(c)):null;return d&&"null"!==d?"{"===d.charAt(0)||"["===d.charAt(0)?b.fromJson(d):d:null},o=function(b){if(!l)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),i.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:"cookie"}),u(b);try{e.removeItem(k(b)),i.removeItem&&a.$broadcast("LocalStorageModule.notification.removeitem",{key:b,storageType:f.storageType})}catch(c){return a.$broadcast("LocalStorageModule.notification.error",c.message),u(b)}return!0},p=function(){if(!l)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),!1;var b=g.length,c=[];for(var d in e)if(d.substr(0,b)===g)try{c.push(d.substr(b))}catch(f){return a.$broadcast("LocalStorageModule.notification.error",f.Description),[]}return c},q=function(b){b=b||"";var c=g.slice(0,-1),d=new RegExp(c+"."+b);if(!l)return a.$broadcast("LocalStorageModule.notification.warning","LOCAL_STORAGE_NOT_SUPPORTED"),v();var f=g.length;for(var h in e)if(d.test(h))try{o(h.substr(f))}catch(i){return a.$broadcast("LocalStorageModule.notification.error",i.message),v()}return!0},r=function(){try{return navigator.cookieEnabled||"cookie"in d&&(d.cookie.length>0||(d.cookie="test").indexOf.call(d.cookie,"test")>-1)}catch(b){return a.$broadcast("LocalStorageModule.notification.error",b.message),!1}},s=function(b,c){if("undefined"==typeof c)return!1;if(!r())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;try{var e="",f=new Date,g="";if(null===c?(f.setTime(f.getTime()+-864e5),e="; expires="+f.toGMTString(),c=""):0!==h.expiry&&(f.setTime(f.getTime()+24*h.expiry*60*60*1e3),e="; expires="+f.toGMTString()),b){var i="; path="+h.path;h.domain&&(g="; domain="+h.domain),d.cookie=k(b)+"="+encodeURIComponent(c)+e+i+g}}catch(j){return a.$broadcast("LocalStorageModule.notification.error",j.message),!1}return!0},t=function(b){if(!r())return a.$broadcast("LocalStorageModule.notification.error","COOKIES_NOT_SUPPORTED"),!1;for(var c=d.cookie&&d.cookie.split(";")||[],e=0;e<c.length;e++){for(var f=c[e];" "===f.charAt(0);)f=f.substring(1,f.length);if(0===f.indexOf(k(b)+"="))return decodeURIComponent(f.substring(g.length+b.length+1,f.length))}return null},u=function(a){s(a,null)},v=function(){for(var a=null,b=g.length,c=d.cookie.split(";"),e=0;e<c.length;e++){for(a=c[e];" "===a.charAt(0);)a=a.substring(1,a.length);var f=a.substring(b,a.indexOf("="));u(f)}},w=function(){return j},x=function(a,c,d){var e=n(c);null===e&&b.isDefined(d)?e=d:b.isObject(e)&&b.isObject(d)&&(e=b.extend(d,e)),a[c]=e,a.$watchCollection(c,function(a){m(c,a)})};return{isSupported:l,getStorageType:w,set:m,add:m,get:n,keys:p,remove:o,clearAll:q,bind:x,deriveKey:k,cookie:{set:s,add:s,get:t,remove:u,clearAll:v}}}]})}(window,window.angular);

@ -1,9 +1,9 @@
{
"name": "angular-local-storage",
"version": "0.1.5",
"version": "0.1.0",
"description": "An Angular module that gives you access to the browsers local storage",
"homepage": "https://github.com/grevory/angular-local-storage",
"main": "./dist/angular-local-storage.js",
"main": "angular-local-storage.js",
"scripts": {
"test": "grunt test"
},
@ -22,17 +22,15 @@
"url": "https://github.com/grevory/angular-local-storage/issues"
},
"devDependencies": {
"time-grunt": "~0.2.9",
"load-grunt-tasks": "~0.3.0",
"grunt-contrib-jshint": "~0.8.0",
"grunt": "~0.4.2",
"grunt-cli": "~0.1.9",
"grunt-contrib-concat": "*",
"grunt-contrib-jshint": "~0.8.0",
"grunt-contrib-uglify": "*",
"grunt-karma": "latest",
"karma": "~0.12.16",
"karma-jasmine": "~0.1.5",
"karma-coverage": "^0.2.6",
"karma-phantomjs-launcher": "~0.1.4",
"load-grunt-tasks": "~0.3.0",
"time-grunt": "~0.2.9"
"grunt-contrib-concat": "*",
"karma": "~0.10",
"grunt-karma": "~0.6.2",
"karma-jasmine": "*"
}
}

@ -1,9 +1,12 @@
(function() {
/* Start angularLocalStorage */
'use strict';
var angularLocalStorage = angular.module('LocalStorageModule', []);
angularLocalStorage.provider('localStorageService', function() {
// You should set a prefix to avoid overwriting any local storage variables from the rest of your app
// e.g. localStorageServiceProvider.setPrefix('yourAppName');
// e.g. localStorageServiceProvider.setPrefix('youAppName');
// With provider you can use config as this:
// myApp.config(function (localStorageServiceProvider) {
// localStorageServiceProvider.prefix = 'yourAppName';
@ -30,13 +33,11 @@ angularLocalStorage.provider('localStorageService', function() {
// Setter for the prefix
this.setPrefix = function(prefix) {
this.prefix = prefix;
return this;
};
// Setter for the storageType
this.setStorageType = function(storageType) {
this.storageType = storageType;
return this;
this.storageType = storageType;
};
// Setter for cookie config
@ -45,13 +46,11 @@ angularLocalStorage.provider('localStorageService', function() {
expiry: exp,
path: path
};
return this;
};
// Setter for cookie domain
this.setStorageCookieDomain = function(domain) {
this.cookie.domain = domain;
return this;
};
// Setter for notification config
@ -61,7 +60,6 @@ angularLocalStorage.provider('localStorageService', function() {
setItem: itemSet,
removeItem: itemRemove
};
return this;
};
this.$get = ['$rootScope', '$window', '$document', '$parse', function($rootScope, $window, $document, $parse) {
@ -85,7 +83,7 @@ angularLocalStorage.provider('localStorageService', function() {
}
var deriveQualifiedKey = function(key) {
return prefix + key;
};
}
// Checks the browser to see if local storage is supported
var browserSupportsLocalStorage = (function () {
try {
@ -118,10 +116,10 @@ angularLocalStorage.provider('localStorageService', function() {
// Example use: localStorageService.add('library','angular');
var addToLocalStorage = function (key, value) {
// Let's convert undefined values to null to get the value consistent
if (isUndefined(value)) {
if (typeof value === "undefined") {
value = null;
} else if (isObject(value) || isArray(value) || isNumber(+value || value)) {
value = toJson(value);
}else if (angular.isObject(value) || angular.isArray(value)) {
value = angular.toJson(value);
}
// If this browser does not support local storage use cookies
@ -137,8 +135,8 @@ angularLocalStorage.provider('localStorageService', function() {
}
try {
if (isObject(value) || isArray(value)) {
value = toJson(value);
if (angular.isObject(value) || angular.isArray(value)) {
value = angular.toJson(value);
}
if (webStorage) {webStorage.setItem(deriveQualifiedKey(key), value)};
if (notify.setItem) {
@ -170,8 +168,8 @@ angularLocalStorage.provider('localStorageService', function() {
return null;
}
if (item.charAt(0) === "{" || item.charAt(0) === "[" || isStringNumber(item)) {
return fromJson(item);
if (item.charAt(0) === "{" || item.charAt(0) === "[") {
return angular.fromJson(item);
}
return item;
@ -264,29 +262,27 @@ angularLocalStorage.provider('localStorageService', function() {
};
// Checks the browser to see if cookies are supported
var browserSupportsCookies = (function() {
var browserSupportsCookies = function() {
try {
return $window.navigator.cookieEnabled ||
return navigator.cookieEnabled ||
("cookie" in $document && ($document.cookie.length > 0 ||
($document.cookie = "test").indexOf.call($document.cookie, "test") > -1));
} catch (e) {
$rootScope.$broadcast('LocalStorageModule.notification.error', e.message);
return false;
}
}());
};
// Directly adds a value to cookies
// Typically used as a fallback is local storage is not available in the browser
// Example use: localStorageService.cookie.add('library','angular');
var addToCookies = function (key, value) {
if (isUndefined(value)) {
if (typeof value === "undefined") {
return false;
} else if(isArray(value) || isObject(value)) {
value = toJson(value);
}
if (!browserSupportsCookies) {
if (!browserSupportsCookies()) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false;
}
@ -322,7 +318,7 @@ angularLocalStorage.provider('localStorageService', function() {
// Directly get a value from a cookie
// Example use: localStorageService.cookie.get('library'); // returns 'angular'
var getFromCookies = function (key) {
if (!browserSupportsCookies) {
if (!browserSupportsCookies()) {
$rootScope.$broadcast('LocalStorageModule.notification.error', 'COOKIES_NOT_SUPPORTED');
return false;
}
@ -336,8 +332,8 @@ angularLocalStorage.provider('localStorageService', function() {
if (thisCookie.indexOf(deriveQualifiedKey(key) + '=') === 0) {
var storedValues = decodeURIComponent(thisCookie.substring(prefix.length + key.length + 1, thisCookie.length))
try{
var obj = JSON.parse(storedValues);
return fromJson(obj)
var obj = JSON.parse(storedValues)
return angular.fromJson(obj)
}catch(e){
return storedValues
}
@ -370,43 +366,40 @@ angularLocalStorage.provider('localStorageService', function() {
return storageType;
};
// Add a listener on scope variable to save its changes to local storage
// Return a function which when called cancels binding
var bindToScope = function(scope, key, def, lsKey) {
lsKey = lsKey || key;
var bindToScope = function(scope, scopeKey, def, lsKey) {
if (!lsKey) {
lsKey = scopeKey;
}
var value = getFromLocalStorage(lsKey);
if (value === null && isDefined(def)) {
if (value === null && angular.isDefined(def)) {
value = def;
} else if (isObject(value) && isObject(def)) {
value = extend(def, value);
} else if (angular.isObject(value) && angular.isObject(def)) {
value = angular.extend(def, value);
}
$parse(key).assign(scope, value);
$parse(scopeKey).assign(scope, value);
return scope.$watch(key, function(newVal) {
scope.$watchCollection(scopeKey, function(newVal) {
addToLocalStorage(lsKey, newVal);
}, isObject(scope[key]));
});
};
// Return localStorageService.length
// ignore keys that not owned
var lengthOfLocalStorage = function() {
var count = 0;
var storage = $window[storageType];
for(var i = 0; i < storage.length; i++) {
if(storage.key(i).indexOf(prefix) === 0 ) {
count++;
var lengthToLocalStorage = function() {
var cant = 0;
for(var iIndex=0; iIndex<localStorage.length; iIndex++){
if( localStorage.key(iIndex).contains(prefix) && localStorage.key(iIndex).indexOf(prefix) === 0 ){
cant++;
}
}
return count;
return cant;
};
return {
isSupported: browserSupportsLocalStorage,
getStorageType: getStorageType,
set: addToLocalStorage,
put: addToLocalStorage,
add: addToLocalStorage, //DEPRECATED
get: getFromLocalStorage,
keys: getKeysForLocalStorage,
@ -414,9 +407,8 @@ angularLocalStorage.provider('localStorageService', function() {
clearAll: clearAllFromLocalStorage,
bind: bindToScope,
deriveKey: deriveQualifiedKey,
length: lengthOfLocalStorage,
length: lengthToLocalStorage,
cookie: {
isSupported: browserSupportsCookies,
set: addToCookies,
add: addToCookies, //DEPRECATED
get: getFromCookies,
@ -426,3 +418,4 @@ angularLocalStorage.provider('localStorageService', function() {
};
}];
});
}).call(this);

@ -1,18 +0,0 @@
/*jshint globalstrict:true*/
'use strict';
var isDefined = angular.isDefined,
isUndefined = angular.isUndefined,
isNumber = angular.isNumber,
isObject = angular.isObject,
isArray = angular.isArray,
extend = angular.extend,
toJson = angular.toJson,
fromJson = angular.fromJson;
// Test if string is only contains numbers
// e.g '1' => true, "'1'" => true
function isStringNumber(num) {
return /^-?\d+\.?\d*$/.test(num.replace(/["']/g, ''));
}

@ -22,27 +22,19 @@ module.exports = function(config) {
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
browsers: ['Chrome'],
// list of files / patterns to load in the browser
files: [
bower + 'angular/angular.js',
bower + 'angular-mocks/angular-mocks.js',
'src/*.js',
'test/mock/*.js',
'src/angular-local-storage.js',
'test/spec/**/*.js'
],
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-coverage'
],
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
@ -52,19 +44,6 @@ module.exports = function(config) {
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true,
reporters: ['progress', 'coverage'],
// preprocessors
preprocessors: {
'src/*.js': ['coverage']
},
// configure the reporter
coverageReporter: {
type : 'lcov',
dir : 'coverage/'
}
singleRun: true
});
};

@ -1,42 +0,0 @@
'use strict';
//Mock localStorage
function localStorageMock() {
var storage = {};
Object.defineProperties(storage, {
setItem: {
value: function(key, value) {
storage[key] = value || '';
},
enumerable: false,
writable: true
},
getItem: {
value: function(key) {
return storage[key];
},
enumerable: false,
writable: true
},
removeItem: {
value: function(key) {
delete storage[key];
},
enumerable: false,
writable: true
},
length: {
get: function() {
return Object.keys(storage).length;
},
enumerable: false
},
key: {
value: function(i) {
var aKeys = Object.keys(storage);
return aKeys[i] || null;
},
enumerable: false
}
});
return storage;
}

@ -3,6 +3,23 @@
describe('localStorageService', function() {
var elmSpy;
//Mock
function localStorageMock() {
var keys = {};
return {
setItem: function(key, value) {
keys[key] = value || '';
},
getItem: function(key) {
return keys[key];
},
removeItem: function(key) {
delete keys[key];
}
};
}
//Actions
function getItem(key) {
return function($window, localStorageService) {
@ -18,14 +35,6 @@ describe('localStorageService', function() {
};
}
function addItemWithPut(key, value) {
return function($window, localStorageService) {
elmSpy = spyOn($window.localStorage, 'setItem').andCallThrough();
localStorageService.put(key, value);
};
}
function removeItem(key) {
return function($window, localStorageService) {
elmSpy = spyOn($window.localStorage, 'removeItem').andCallThrough();
@ -70,12 +79,6 @@ describe('localStorageService', function() {
};
}
function expectCookieSupporting(expected) {
return function(localStorageService) {
expect(localStorageService.cookie.isSupported).toEqual(expected);
};
}
function expectDomain(domain) {
return function($document, localStorageService) {
localStorageService.set('foo','bar'); //Should trigger first time
@ -145,17 +148,6 @@ describe('localStorageService', function() {
expectAdding('ls.foo', 'bar')
));
it('should add key to localeStorage null if value not provided', inject(
addItem('foo'),
expectAdding('ls.foo', null)
));
it('should add key to localStorage using put method', inject(
addItemWithPut('key', 777),
expectAdding('ls.key', angular.toJson(777)),
expectMatching('key', 777)
));
it('should support to set custom prefix', function() {
module(setPrefix('myApp'));
inject(
@ -164,19 +156,6 @@ describe('localStorageService', function() {
);
});
it('should be able to chain functions in the config phase', function() {
module(function(localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('chain')
.setNotify(false, true)
.setStorageType('session');
});
inject(function(localStorageService) {
expect(localStorageService.deriveKey('foo')).toEqual('chain.foo');
expect(localStorageService.getStorageType()).toEqual('session');
});
});
it('should be able to return the derive key', function() {
module(setPrefix('myApp'));
inject(function(localStorageService) {
@ -202,38 +181,6 @@ describe('localStorageService', function() {
);
});
it('should be able to set and get integers', function() {
inject(
addItem('key', 777),
expectAdding('ls.key', angular.toJson(777)),
expectMatching('key', 777)
);
});
it('should be able to set and get float numbers', function() {
inject(
addItem('key', 123.123),
expectAdding('ls.key', angular.toJson(123.123)),
expectMatching('key', 123.123)
);
});
it('should be able to set and get strings', function() {
inject(
addItem('key', 'string'),
expectAdding('ls.key', 'string'),
expectMatching('key', 'string')
);
});
it('should be able to set and get numbers as a strings', function() {
inject(
addItem('key', '777'),
expectAdding('ls.key', angular.toJson('777')),
expectMatching('key', '777')
);
});
it('should be able to get items', inject(
getItem('key'),
expectGetting('ls.key')
@ -280,17 +227,6 @@ describe('localStorageService', function() {
});
});
it('should be able to notify/broadcasting if set', function() {
module(setNotify(true, true));
inject(function($rootScope, localStorageService) {
var spy = spyOn($rootScope, '$broadcast');
localStorageService.set('a8m', 'foobar');
localStorageService.remove('a8m', 'foobar');
expect(spy.callCount).toEqual(2);
});
});
it('should be able to bind to scope', inject(function($rootScope, localStorageService) {
localStorageService.set('property', 'oldValue');
@ -302,23 +238,6 @@ describe('localStorageService', function() {
expect($rootScope.property).toEqual(localStorageService.get('property'));
}));
it('should be able to unbind from scope variable', inject(function($rootScope, localStorageService) {
localStorageService.set('property', 'oldValue');
var lsUnbind = localStorageService.bind($rootScope, 'property');
$rootScope.property = 'newValue';
$rootScope.$digest();
expect($rootScope.property).toEqual(localStorageService.get('property'));
lsUnbind();
$rootScope.property = 'anotherValue';
$rootScope.$digest();
expect($rootScope.property).not.toEqual(localStorageService.get('property'));
}));
it('should be able to bind to properties of objects', inject(function($rootScope, localStorageService) {
localStorageService.set('obj.property', 'oldValue');
@ -345,61 +264,6 @@ describe('localStorageService', function() {
expect($rootScope.property).toEqual(localStorageService.get('lsProperty'));
}));
it('should $watch with deep comparison only for objects', inject(function($rootScope, localStorageService) {
var mocks = [{}, [], 'string', 90, false];
var expectation = [true, true, false, false, false];
var results = [];
spyOn($rootScope, '$watch').andCallFake(function(key, func, eq) {
results.push(eq);
});
mocks.forEach(function(elm, i) {
localStorageService.set('mock' + i, elm);
localStorageService.bind($rootScope, 'mock' + i);
});
expect(results).toEqual(expectation);
}));
it('should be able to return it\'s owned keys amount', inject(
function(localStorageService, $window) {
for(var i = 0; i < 10; i++) {
localStorageService.set('key' + i, 'val' + i);
$window.localStorage.setItem('key' + i, 'val' + i);
}
expect(localStorageService.length()).toEqual(10);
expect($window.localStorage.length).toEqual(20);
}));
it('should be able to clear all owned keys from storage',inject(function($window, localStorageService) {
for(var i = 0; i < 10; i++) {
localStorageService.set('key' + i, 'val' + i);
$window.localStorage.setItem('key' + i, 'val' + i);
}
localStorageService.clearAll();
//remove only owned keys
for(var l = 0; l < 10; l++) {
expect(localStorageService.get('key' + l)).toEqual(null);
expect($window.localStorage.getItem('key' + l)).toEqual('val' + l);
}
}));
it('should return array of all owned keys', inject(function($window, localStorageService) {
//set keys
for(var i = 0; i < 10; i++) {
//localStorageService
localStorageService.set('ownKey' + i, 'val' + i);
//window.localStorage
$window.localStorage.setItem('windowKey' + i, 'val' + i);
}
localStorageService.keys().forEach(function(el, i) {
expect(el).toEqual('ownKey' + i);
});
}));
//sessionStorage
describe('SessionStorage', function() {
@ -450,10 +314,7 @@ describe('localStorageService', function() {
beforeEach(module('LocalStorageModule', function($provide) {
$provide.value('$window', {
localStorage: false,
sessionStorage: false,
navigator: {
cookieEnabled: true
}
sessionStorage: false
});
$provide.value('$document', {
cookie: ''
@ -464,10 +325,6 @@ describe('localStorageService', function() {
expectSupporting(false)
));
it('cookie.isSupported should be true if cookies are enabled', inject(
expectCookieSupporting(true)
));
it('fallback storage type should be cookie', inject(
expectStorageTyping('cookie')
));
@ -493,50 +350,6 @@ describe('localStorageService', function() {
expect(localStorageService.get('cookieKey')).toEqual('');
}));
it('should be able to set and get objects from cookie', inject(function(localStorageService) {
//use as a fallback
localStorageService.set('cookieKey', { a: { b: 1 } });
expect(localStorageService.get('cookieKey')).toEqual({ a: { b: 1 } });
//use directly
localStorageService.cookie.set('cookieKey', { a: 2 });
expect(localStorageService.cookie.get('cookieKey')).toEqual({ a: 2 });
}));
it('should be able to set and get arrays from cookie', inject(function(localStorageService) {
//use as a fallback
localStorageService.set('cookieKey', [1, 2, 3, [ 1, 2, 3 ]]);
expect(localStorageService.get('cookieKey')).toEqual([1, 2, 3, [ 1, 2, 3 ]]);
//use directly
localStorageService.cookie.set('cookieKey', ['foo', 'bar']);
expect(localStorageService.cookie.get('cookieKey')).toEqual(['foo', 'bar']);
}));
it('should be able to clear all owned keys from cookie', inject(function(localStorageService, $document) {
localStorageService.set('ownKey1', 1);
$document.cookie = 'username=John Doe';
localStorageService.clearAll();
expect(localStorageService.get('ownKey1')).toEqual(null);
expect($document.cookie).not.toEqual('');
}));
it('should be broadcast on adding item', function() {
module(setNotify(true, false));
inject(function($rootScope, localStorageService) {
var spy = spyOn($rootScope, '$broadcast');
localStorageService.set('a8m', 'foobar');
expect(spy).toHaveBeenCalled();
});
});
it('should be broadcast on removing item', function() {
module(setNotify(false, true));
inject(function($rootScope, localStorageService) {
var spy = spyOn($rootScope, '$broadcast');
localStorageService.remove('a8m', 'foobar');
expect(spy).toHaveBeenCalled();
});
});
Date.prototype.addDays = function(days) {
var date = new Date(this.getTime());
date.setDate(date.getDate() + days);
@ -544,22 +357,4 @@ describe('localStorageService', function() {
};
});
//cookie disabled
describe('No Cookie', function() {
beforeEach(module('LocalStorageModule', function($provide) {
$provide.value('$window', {
navigator: {
cookieEnabled: false
}
});
$provide.value('$document', {
});
}));
it('cookie.isSupported should be false if cookies are disabled', inject(
expectCookieSupporting(false)
));
});
});