Angular's cookie read/write method, angularcookie read/write
AngularJS encapsulates a separate module for cookie operations, the module name is ngCookies, if you want to use the need to first introduce angular-cookies.js in the page:
<script src="js/angular.min.js"></script><script src="js/angular-cookies.js"></script>
Then inject the ngCookies module into the dependent modules of our custom modules:
var app = angular.module("myApp",['ngCookies']);
The ngCookies module provides two services related to the reading and writing of cookies: $ cookies and $ cookieStroe. Regardless of the type used, you must first inject it into the controller. To compare the differences between the two, inject it into the controller:
app.controller('namesCtrl', ['$cookies','$cookieStore',function($cookies, $cookieStore){}]);
Set the cookie using the put () method:
$cookies.put(key, value[, options]);
$cookieStore.put(key, value);
For example, set a cookie named "userName" with the value "yangmin ":
// Use $ cookies to set cookies $ cookies. put ('username', 'yangmin ');
// Use $ cookieStore to set cookie $ cookieStore. put ('username', 'yangmin ');
Use the get () method to obtain the cookie:
$cookies.get(key);
$cookieStore.get(key);
For example, obtain the "userName" set above ":
$cookies.get(userName);//yangmin
$cookieStore.get("userName"); //yangmin
Use remove () to delete a cookie ():
$cookies.remove(key[, options]);
$cookieStore.remove(key);
For example, deleting "userName"
$cookies.remove("userName");
$cookieStore.remove("userName");
Difference between $ cookies and $ cookieStore:
1. the cookie value set by $ cookies is generally a string, and $ cookieStroe can be used to set strings, objects, arrays, and so on.
$cookies.put("person",{name:"Amy",age:23});var person = $cookies.get("person");console.log(person.age);//undefined
$cookieStore.put("person",{name:"Amy",age:23});var person = $cookieStore.get("person");console.log(person.age);//23
2. $ cookies can be set as parameters. For example, you can set the cookie expiration time. $ CookieStore cannot set parameters
Var expireDate = new Date (); expireDate. setDate (expireDate. getDate () + 1); $ cookies. put ("userName", "yangmin", {'expires': expireDate}); // "userName" expires one day later
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.