From fc925d4e34f99e3c16fcddaa02f0abcf3be64837 Mon Sep 17 00:00:00 2001 From: Caitlin Potter Date: Tue, 18 Mar 2014 13:13:08 -0400 Subject: [PATCH] fix(ngCookie): convert non-string values to string Previously, non-string values stored in $cookies would be removed, without warning the user, and causing difficulty debugging. Now, the value is converted to string before being stored, and the value is not dropped. Serialization may be customized using the toString() method of an object's prototype. Closes #6151 Closes #6220 --- src/ngCookies/cookies.js | 10 ++++------ test/ngCookies/cookiesSpec.js | 18 ++++++++++++++---- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/ngCookies/cookies.js b/src/ngCookies/cookies.js index ccfae23be86e..4f97c8dd17f3 100644 --- a/src/ngCookies/cookies.js +++ b/src/ngCookies/cookies.js @@ -95,12 +95,10 @@ angular.module('ngCookies', ['ng']). for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { - if (angular.isDefined(lastCookies[name])) { - cookies[name] = lastCookies[name]; - } else { - delete cookies[name]; - } - } else if (value !== lastCookies[name]) { + value = '' + value; + cookies[name] = value; + } + if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } diff --git a/test/ngCookies/cookiesSpec.js b/test/ngCookies/cookiesSpec.js index 674c27748f11..1d669c1c6b8a 100644 --- a/test/ngCookies/cookiesSpec.js +++ b/test/ngCookies/cookiesSpec.js @@ -45,15 +45,25 @@ describe('$cookies', function() { })); - it('should drop or reset any cookie that was set to a non-string value', + it('should convert non-string values to string', inject(function($cookies, $browser, $rootScope) { $cookies.nonString = [1, 2, 3]; $cookies.nullVal = null; $cookies.undefVal = undefined; - $cookies.preexisting = function() {}; + var preexisting = $cookies.preexisting = function() {}; $rootScope.$digest(); - expect($browser.cookies()).toEqual({'preexisting': 'oldCookie'}); - expect($cookies).toEqual({'preexisting': 'oldCookie'}); + expect($browser.cookies()).toEqual({ + 'preexisting': '' + preexisting, + 'nonString': '1,2,3', + 'nullVal': 'null', + 'undefVal': 'undefined' + }); + expect($cookies).toEqual({ + 'preexisting': '' + preexisting, + 'nonString': '1,2,3', + 'nullVal': 'null', + 'undefVal': 'undefined' + }); }));