[英]How to use cookies? Angular-cookies
我是Angular和cookies的新手,我有一個HTML模板,我需要在用戶第一次訪問我的應用時顯示該模板。 但是,下次他們訪問時,他們應該不再看到該模板並看到默認模板。
但是,這兩個解決方案都引發了錯誤,在第一個鏈接==
不起作用時,下一個示例string is not a function
下面的代碼如何檢查是否有cookie,如果沒有則創建cookie。
// Controller for Dashboard
app.controller('DashboardController', ['$scope', '$cookies', '$cookieStore', function ($scope, $cookies, $cookieStore) {
// if cookie does not exits show welcome template
// create cookie
// if cookie welcome exits show default template
$scope.welcome = $cookieStore.get('welcome');
$scope.checkCookie = function(welcome){
$scope.welcome = welcome;
$cookieStore.put('cookie', welcome);
};
// $cookieStore.put("name","my name");
// $cookieStore.get("name") = "my name";
// $cookieStore.remove("name");
}]);
使用有角度和角度的cookie,讀取和寫入cookie非常容易。 您首先需要在您的應用和控制器中注入$ cookies依賴項。
然后,您可以從$ cookie參數中分配和檢索值。
以下示例將顯示首次登錄用戶的歡迎消息,以及其他人的問候消息。
angular.module('CookieDemo', ['ngCookies'])
.controller('DashboardController', ['$scope', '$cookies', function ($scope, $cookies) {
// Retrieve the cookie and set it to userName, in first visit it will be an empty string
$scope.userName = $cookies.userName || "";
// Set the cookie for next visit of the user
$cookies.userName = 'testUser';
}]);
<body ng-app="CookieDemo" ng-controller="DashboardController">
<h1 ng-show="userName.length > 0">Hello {{userName}}</h1>
<h1 ng-hide="userName.length > 0">This is your first visit.</h1>
</body>
這是掠奪者 。
我不明白為什么決定使用它,如果有可能寫一個模塊?
define('cookies',function(){
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : undefined
}
function setCookie(name, value, props) {
props = props || {}
var exp = props.expires
if (typeof exp == "number" && exp) {
var d = new Date()
d.setTime(d.getTime() + exp*1000)
exp = props.expires = d
}
if(exp && exp.toUTCString) { props.expires = exp.toUTCString() }
value = encodeURIComponent(value)
var updatedCookie = name + "=" + value
for(var propName in props){
updatedCookie += "; " + propName
var propValue = props[propName]
if(propValue !== true){ updatedCookie += "=" + propValue }
}
document.cookie = updatedCookie
}
function deleteCookie(name) {
setCookie(name, null, { expires: -1 })
}
return {
getCookie:getCookie,
setCookie:setCookie,
deleteCookie:deleteCookie
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.