Angularjs cookie 操作實例詳解
摘要
現(xiàn)在很多app采用內(nèi)嵌h5的方式進行開發(fā),有些數(shù)據(jù)會存在webveiw的cookie中,那么如果使用angularjs開發(fā)單頁應(yīng)用,就需要用到angularjs的cookie操作。這里提供一個簡單的學(xué)習(xí)demo。方便快速上手。
一個例子
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" ng-app="myapp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="Scripts/angular.js"></script> <script src="Scripts/angular-cookies.js"></script> <script> angular.module("myapp", ["ngCookies"]).controller("TestController", function ($cookies) { // Put cookie $cookies.put('mytest', 'mytest'); // Get cookie var mytestCookie = $cookies.get('mytest'); console.log(mytestCookie) // Removing a cookie // $cookie.remove('mytest'); console.log($cookies.get('mytest')); }); </script> </head> <body ng-controller="TestController"> </body> </html>
測試結(jié)果
可以看到上面結(jié)果設(shè)置成功了,但過期時間是session,這種cookie是跟當(dāng)前會話相同了,也就是關(guān)閉瀏覽器之后就會消失,這是因為我們沒有設(shè)置cookie的過期時間造成了,可以通過下面的方式設(shè)置過期時間。
var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + 30);//設(shè)置cookie保存30天 // Put cookie $cookies.put('mytest', 'mytest', { 'expires': expireDate });
總結(jié)
這里需要注意,在網(wǎng)上看到很多實用$cookieStore的,確實可以設(shè)置成功,但設(shè)置過期時間的時候會失效,建議采用$cookies
以上所述是小編給大家介紹的Angularjs cookie 操作實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
AngularJS ngModel實現(xiàn)指令與輸入直接的數(shù)據(jù)通信
這篇文章主要介紹了AngularJS ngModel實現(xiàn)指令與輸入直接的數(shù)據(jù)通信的相關(guān)資料,需要的朋友可以參考下2016-09-09Angular應(yīng)用里異步打開對話框技術(shù)詳解
這篇文章主要為大家介紹了Angular應(yīng)用里異步打開對話框技術(shù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12使用 Github Actions 自動部署 Angular 應(yīng)用到 Github Pages的方法
這篇文章主要介紹了使用 Github Actions 自動部署 Angular 應(yīng)用到 Github Pages,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07