angular.js - How to set a cookie to expire after 24:00 today in angularjs?
phpcn_u1582
phpcn_u1582 2017-05-15 16:55:13
0
2
784

The cookie stores a piece of user participation information. This information is expected to be valid within today and expire after 24:00. How to set it?

phpcn_u1582
phpcn_u1582

reply all(2)
巴扎黑

What I say below are all operated in Angular 1.4.x version.

1. First you need to load the ngCookies module, and then add this dependency where you need it.
2. Then you can refer to $cookies here for specific methods.
3. The general method is as follows:

    $cookies.put(key, value, [options]); // 存储一个字符串
    $cookies.putObject(key, value, [options]); // 存储一个对象
    
    $cookies.get(key); // 获取一个cookie字符串
    $cookies.getObject(key); // 获取一个cookies对象

4. The cookie time can be set by yourself. You can set some options through $cookiesProvider. For details, see $cookiesProvider here.
5. I have a small example here that you can take a look at, demo
6. The specific code is as follows:

index.html
 <body ng-app="MyApp">
    <h1>Angular $cookies</h1>
    <h2>打开控制台,看看Cookies</h2>
    <p ng-controller="MyController as vm">
        {{vm.data}}
    </p>
</body>

app.js
    (function(){
angular.module('MyApp', ['ngCookies'])
    .config(cookiesConfig)
    .controller('MyController', MyController);

cookiesConfig.$inject = ['$cookiesProvider']
MyController.$inject = ['$cookies'];

function cookiesConfig($cookiesProvider){
    var date = new Date();
    date.setDate(date.getDate() + 1);
    var expires = date;
    console.log(expires);
    $cookiesProvider.expires = expires;
}

function MyController($cookies){
    var vm = this;
    vm.person = {
        name: 'dreamapple',
        age: 22,
        address: 'China'
    };
    $cookies.putObject('person', vm.person);

    vm.data = $cookies.getObject('person');
}

})();
phpcn_u1582

The cookie time is set on the server side, not on the web page. The server side is simple. Just calculate the expiration time. If it is Java, it is recommended to use joda time. The following is an example of using joda time to set the 24-point expiration:

DateTime now = DateTime.now();
DateTime endOfToday = now.withTimeAtStartOfDay().plusDays(1);
Cookie cookie = new Cookie(key, value);
cookie.setMaxAge(Seconds.secondsBetween(now, endOfToday).getSeconds());
cookie.setDomain(domain);
cookie.setPath("/");
response.addCookie(cookie);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template