From 887b6828158b6d7c2b3addf3527c3453dc8f6156 Mon Sep 17 00:00:00 2001 From: Den Teresh Date: Thu, 9 Oct 2014 14:59:11 +1300 Subject: [PATCH] localStorageService.bind to return a deregistration function --- src/angular-local-storage.js | 4 +++- test/spec/localStorageSpec.js | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/angular-local-storage.js b/src/angular-local-storage.js index 9b2e58e..6b00fec 100644 --- a/src/angular-local-storage.js +++ b/src/angular-local-storage.js @@ -365,6 +365,8 @@ 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, scopeKey, def, lsKey) { if (!lsKey) { lsKey = scopeKey; @@ -380,7 +382,7 @@ angularLocalStorage.provider('localStorageService', function() { $parse(scopeKey).assign(scope, value); - scope.$watchCollection(scopeKey, function(newVal) { + return scope.$watchCollection(scopeKey, function(newVal) { addToLocalStorage(lsKey, newVal); }); }; diff --git a/test/spec/localStorageSpec.js b/test/spec/localStorageSpec.js index adfe4d4..14551c5 100644 --- a/test/spec/localStorageSpec.js +++ b/test/spec/localStorageSpec.js @@ -277,6 +277,23 @@ 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');