最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set a cookie in Angular if one does not exist - Stack Overflow

programmeradmin2浏览0评论

I want to see if a cookie has been set in Angular, and if it doesn't find a cookie, it will create a new one.

Right now I'm using this:

    if ($cookies.get('storedLCookie').length != 0) {
       $cookies.put('storedLCookie','Oatmeal');
    }

It doesn't seem to be working, though. Is there another way to test if a cookie is set in Angular?

I want to see if a cookie has been set in Angular, and if it doesn't find a cookie, it will create a new one.

Right now I'm using this:

    if ($cookies.get('storedLCookie').length != 0) {
       $cookies.put('storedLCookie','Oatmeal');
    }

It doesn't seem to be working, though. Is there another way to test if a cookie is set in Angular?

Share Improve this question asked Mar 23, 2016 at 6:22 ArtvaderArtvader 9585 gold badges16 silver badges32 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

you can simply do this to check it:

var favoriteCookie = $cookies.get('cookieval');

  if ( favoriteCookie ) {
    //exists
  } else {
    //not exists
  }

The data store in cookie is string or number. When it's a number, you should't judge it by length. Test the following:

var a = 3
console.log(a.length) // will return undefined

I think you can just write the following instead:

if ($cookies.get('storedLCookie')) {
   $cookies.put('storedLCookie','Oatmeal');
}
发布评论

评论列表(0)

  1. 暂无评论