I can get a cookie as the following. I call this cookie in my module and pass it as a parameter.
How do I change the code to get a cookie so that its all in standard angularjs code?
$(document).ready(function() {
Cookie();
});
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function Cookie() {
var cookie = getCookie('Id');
}
function Module($http) {
var self = this;
self.$http = $http;
self.CookieID = getCookie('Id');
self.test = function() {
var params = {
testId: self.CookieID
}
}
}
Angular ngCookies
First include angular-cookies.js in your HTML:
<script src="angular.js">
<script src="angular-cookies.js">
Then load the module in your application by adding it as a dependent module:
angular.module('app', ['ngCookies']);
Usage Example
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
}]);
jQuery
Set Cookie
$.cookie("my_cookie", value);
Set Cookie with Expiration (in days) and Path
$.cookie("my_cookie", value, { expires: 1, path: '/' });
Remove Cookie
$.removeCookie("my_cookie");
Have you tried $cookies ?
Secondly you could use jQuery cookie - if AngularJs cookie won't do for you.
Example:
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
}]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.