Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular操作cookies方法 #19

Closed
Wscats opened this issue May 20, 2016 · 0 comments
Closed

Angular操作cookies方法 #19

Wscats opened this issue May 20, 2016 · 0 comments
Labels

Comments

@Wscats
Copy link
Owner

Wscats commented May 20, 2016

var setCookie = function(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
    //$cookies[name] = value;
};

这是用Javascript写的方法去设置

var getCookie = function(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

这是用Javascript写的方法去读取
其实angular也有相应的方法去操作cookies的,加载这两个module的依赖文件

<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-cookies.min.js"></script>

源码是这样的

function(a, b, c) {
    "use strict";
    b.module("ngCookies", ["ng"]).factory("$cookies", ["$rootScope", "$browser",
        function(a, d) {
            function e() {
                var a, e, f, i;
                for (a in h) k(g[a]) && d.cookies(a, c);
                for (a in g) e = g[a], b.isString(e) ? e !== h[a] && (d.cookies(a, e), i = !0) : b.isDefined(h[a]) ? g[a] = h[a] : delete g[a];
                if (i) {
                    i = !1, f = d.cookies();
                    for (a in g) g[a] !== f[a] && (k(f[a]) ? delete g[a] : g[a] = f[a], i = !0)
                }
            }
            var f, g = {},
                h = {},
                i = !1,
                j = b.copy,
                k = b.isUndefined;
            return d.addPollFn(function() {
                var b = d.cookies();
                f != b && (f = b, j(b, h), j(b, g), i && a.$apply())
            })(), i = !0, a.$watch(e), g
        }
    ]).factory("$cookieStore", ["$cookies",
        function(a) {
            return {
                get: function(c) {
                    var d = a[c];
                    return d ? b.fromJson(d) : d
                },
                put: function(c, d) {
                    a[c] = b.toJson(d)
                },
                remove: function(b) {
                    delete a[b]
                }
            }
        }
    ])
}(window, window.angular)

$cookies[name] = value;
这个是angular设置cookies方法
$cookieStore
提供一个被session cookies支持的键值对(字符串-对象)存储。被存入和取出的对象将自动通过angular的toJson/fromJson进行序列化/反序列化。
$cookies
提供浏览器cookies的读/写访问操作。
这两个都要引入ngCookies模块才能使用,这个模块在1.4版本之后就有了
从源码中得知$cookieStore返回了三个方法get put remove 他们分别用toJson/fromJson进行序列化/反序列化

简单的写了几个例子来测试下

<!DOCTYPE html>
<html ng-app="WsCatsApp" ng-controller="aswController">

    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
    <script src="http://code.angularjs.org/1.2.9/angular-cookies.min.js"></script>

    <body>
        {{title}}
    </body>
    <script>
        var WsCatsApp = angular.module('WsCatsApp', ['ngCookies']);
        WsCatsApp.controller('aswController', function($cookies, $cookieStore, $scope) {
            $cookies.name = 'wscats';
            $scope.title = "Hello, i'm wscats :)";
            $cookieStore.put("skill", "##");
            //删除cookies
            $cookieStore.remove("name");
            //设置过期日期
            var time = new Date().getTime() + 5000;
            $cookieStore.put("cookie", "Hello wsscat", {
                expires: new Date(new Date().getTime() + 5000)
            });

            $cookieStore.put("objCookie", {
                value: "wsscat cat cat",
                age: "3",
            }, {
                expires: new Date(new Date().getTime() + 5000)
            });
            console.log($cookies);
            console.log($cookies['objCookie']);
        })
    </script>

</html>

其实平时我们这样就可以把自己需要的cookies设置进去
$cookies.name = 'wscats';
但是当我们要设置一个有效时间的时候我们就用这样的方法把它设置进去

var time = new Date().getTime() + 5000;
$cookieStore.put("cookie", "Hello wsscat", {
    expires: new Date(new Date().getTime() + 5000)
});

我们还可以进行删除等操作
$cookieStore.remove("name");

@Wscats Wscats added the notes label Jun 3, 2016
@Wscats Wscats closed this as completed Aug 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant