且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在AngularJS中设置cookie的过期日期

更新时间:2023-01-15 10:47:14

对于1.4:
如在这里的注释和下面的其他人,从1.4,Angular的本地cookie支持现在提供修改Cookie的能力:

For 1.4: As noted in the comment here and others below, as of 1.4, Angular's native cookie support now provides the ability to edit cookies:


由于38fbe3ee,$ cookies将不再公开属性,
表示当前浏览器cookie值。 $ cookies不再轮询
浏览器更改cookie,不再将cookie
值复制到$ cookies对象上。

Due to 38fbe3ee, $cookies will no longer expose properties that represent the current browser cookie values. $cookies no longer polls the browser for changes to the cookies and no longer copies cookie values onto the $cookies object.

因为轮询是昂贵的,并且导致
问题

实际浏览器cookie值不正确地同步(添加原来
的原因是允许不同选项卡之间的通信,但是有
更好的方法今天这样做,例如localStorage。)

This was changed because the polling is expensive and caused issues with the $cookies properties not synchronizing correctly with the actual browser cookie values (The reason the polling was originally added was to allow communication between different tabs, but there are better ways to do this today, for example localStorage.)

$ cookies上的新API如下:

The new API on $cookies is as follows:

get put getObject putObject getAll remove你必须明确使用上面的
方法来访问cookie数据。这也意味着你
不能再观察$ cookies中的属性来检测
在浏览器cookie上发生的变化。

get put getObject putObject getAll remove You must explictly use the methods above in order to access cookie data. This also means that you can no longer watch the properties on $cookies to detect changes that occur on the browsers cookies.

此功能一般只需要第三方库
在运行时以编程方式更改cookie。如果你依赖这个
,那么你必须写出可以对第三方
库做出反应的代码,或者实现你自己的投票
机制。

This feature is generally only needed if a 3rd party library was programmatically changing the cookies at runtime. If you rely on this then you must either write code that can react to the 3rd party library making the changes to cookies or implement your own polling mechanism.

实际实现是通过 $ cookiesProvider 对象,您可以通过 put / code> 呼叫。

The actual implementation is done via a $cookiesProvider object, which can be passed via the put call.

对于1.3及以下版本:
对于那些已经尽力避免加载jQuery插件的人,这似乎是一个很好的替代角度 - https://github.com/ivpusic/angular-cookie

For 1.3 and below: For those of you who have done your best to avoid having to load jQuery plugins, this appears to be a nice replacement for angular - https://github.com/ivpusic/angular-cookie