Angularjs provides a good $cookies and $cookiestore API for handling cookies. Now let’s see how to use $cookies and $cookiestore in angular.
Step 1 – install ngcookies and introduce it into the system
We can use NPM or bower to install ng cookies and paste the GitHub address
https://github.com/angular/bower-angular-cookies
After installation, we can directly introduce our index.html :
<script></script>
Step 2 – introduce ngcookies into the angular module and inject them into the controller
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', '$cookieStore',function($cookies, $cookieStore) {
}]);
Step 3 – using $cookies and $cookiestore
After step 1-2, we can use $cookies and $cookiestore happily.
After injection into the controller, we can use the browser controller to see what methods they provide.
1.$cookies
Obviously, we can use $cookies to add, query and delete cookies.
$cookies provides put and putobject methods to add cookies.
$cookies.put('userName','wws');
$cookies.putObject('user', {'name': 'wws'});
We can see the results through the browser’s debugging tool
Now that cookies have been set in, we can use the get method provided by $cookies to get cookies. Direct mapping
In some cases, we need to clear the cookies manually. At this time, we can use the remove method provided by $cookies.
2.$cookieStore
The $cookiestore provides fewer methods than $cookies, and the calling method is also simple and convenient.
PS: if your ng version is 1.4. X, use $cookies.