0

When I was working with angular cookies, I found out that only strings are accepted by $cookies and stored in browser's cookie when set. i.e

If I set the following cookies

$cookies.id = 12345;
$cookies.name = "Prasad";

Only $cookies.name is set in the browser. So I had to change it to

$cookies.id = "12345";

to make it work.

here is the fiddle link to show the demo.

I've tried to check the angular source code to see why and found that they are deliberately checking for the value to be isString.

Is there any specific reason why they are accepting only string values. Couldn't we just allow integers also and convert to string while adding to browser cookie.

Thanks!

Prasad K - Google
  • 2,584
  • 1
  • 16
  • 18

1 Answers1

0

The main reason is probably that that the value of a cookie is always stored as a string in the browser. Sure, Angular could allow you to save it as an int when using the service and then just convert it before creating the cookie, the problem is that people would then assume that when they read that cookie later on the value would still be an int (that's how they saved it after all).

It wouldn't, it would be a string.

Angular seems to reason (I personally agree) that it is better to be strict up front. Force input to be the same as output so that people don't misunderstand what they will be getting back when they read the cookie.

Erik Honn
  • 7,576
  • 5
  • 33
  • 42
  • In theory Angular could encode something into the string and then use that to determine how it should return the data later on, but $cookies is kind of primitive. It doesn't even let you set a path on your cookies. – Erik Honn Nov 18 '13 at 14:12
  • umm okay!! But I feel it's more intuitive if angularjs allows it instead of letting developers convert it into a string manually (such id+'') and set to $cookies. – Prasad K - Google Nov 18 '13 at 15:18