[Angularjs]cookie操作

摘要

现在很多app采用内嵌h5的方式进行开发,有些数据会存在webveiw的cookie中,那么如果使用angularjs开发单页应用,就需要用到angularjs的cookie操作。这里提供一个简单的学习demo。方便快速上手。

一个例子

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="myapp">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/angular-cookies.js"></script>
    <script>
        angular.module("myapp", ["ngCookies"]).controller("TestController", function ($cookies) {         // Put cookie
            $cookies.put('mytest', 'mytest');
            // Get cookie
            var mytestCookie = $cookies.get('mytest');
            console.log(mytestCookie)
            // Removing a cookie
            // $cookie.remove('mytest');
            console.log($cookies.get('mytest'));
        });
    </script>
</head>
<body ng-controller="TestController">

</body>
</html>

测试结果

可以看到上面结果设置成功了,但过期时间是session,这种cookie是跟当前会话相同了,也就是关闭浏览器之后就会消失,这是因为我们没有设置cookie的过期时间造成了,可以通过下面的方式设置过期时间。

    var expireDate = new Date();
            expireDate.setDate(expireDate.getDate() + 30);//设置cookie保存30天
            // Put cookie
            $cookies.put('mytest', 'mytest', { 'expires': expireDate });

总结

这里需要注意,在网上看到很多实用$cookieStore的,确实可以设置成功,但设置过期时间的时候会失效,建议采用$cookies

原文地址:https://www.cnblogs.com/wolf-sun/p/7600432.html