2014-11-06 75 views
1

我是Angular和cookies的新手,我有一個HTML模板,我需要在用戶第一次訪問我的應用時顯示。但是,他們下次訪問時,他們不應再看到該模板並查看默認模板。如何使用cookies? Angular-cookies

到目前爲止,我找到解決方案發布herehere

但是這兩種解決方案扔的錯誤,在第一環節==沒有工作,下面的例子中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"); 
}]); 

回答

1

讀取和寫入cookie是角和角餅乾很容易。您首先需要在應用程序和控制器中注入$ cookie依賴項。

然後您可以從$ 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> 

這裏是plunker

1

我不明白爲什麼決定使用它,如果有可能寫一個模塊?

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 
     } 
}) 
+0

使用Angular時,不需要編寫自己的模塊。只需使用ngCookies作爲接受的響應即可。 – sfuqua 2015-12-12 21:53:19