2014-11-06 46 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