我可以获得以下cookie。我在我的模块中调用此cookie并将其作为参数传递。
如何更改代码以获取cookie以使其全部采用标准angularjs代码?
$(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
}
}
}
答案 0 :(得分:3)
Angular ngCookies
首先在HTML中包含angular-cookies.js:
<script src="angular.js">
<script src="angular-cookies.js">
然后通过将模块添加为依赖模块来加载应用程序中的模块:
angular.module('app', ['ngCookies']);
用法示例
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 强>
设置Cookie
$.cookie("my_cookie", value);
将Cookie设置为有效期(以天为单位)和路径
$.cookie("my_cookie", value, { expires: 1, path: '/' });
删除Cookie
$.removeCookie("my_cookie");
答案 1 :(得分:0)
你试过$cookies吗?
其次你可以使用jQuery cookie - 如果AngularJs cookie不适合你。
示例:
angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
// Retrieving a cookie
var favoriteCookie = $cookies.get('myFavorite');
// Setting a cookie
$cookies.put('myFavorite', 'oatmeal');
}]);