Angularjs cookie 操作實(shí)例詳解
摘要
現(xiàn)在很多app采用內(nèi)嵌h5的方式進(jìn)行開發(fā),有些數(shù)據(jù)會(huì)存在webveiw的cookie中,那么如果使用angularjs開發(fā)單頁應(yīng)用,就需要用到angularjs的cookie操作。這里提供一個(gè)簡單的學(xué)習(xí)demo。方便快速上手。
一個(gè)例子
<!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>
測(cè)試結(jié)果
可以看到上面結(jié)果設(shè)置成功了,但過期時(shí)間是session,這種cookie是跟當(dāng)前會(huì)話相同了,也就是關(guān)閉瀏覽器之后就會(huì)消失,這是因?yàn)槲覀儧]有設(shè)置cookie的過期時(shí)間造成了,可以通過下面的方式設(shè)置過期時(shí)間。
var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + 30);//設(shè)置cookie保存30天 // Put cookie $cookies.put('mytest', 'mytest', { 'expires': expireDate });
總結(jié)
這里需要注意,在網(wǎng)上看到很多實(shí)用$cookieStore的,確實(shí)可以設(shè)置成功,但設(shè)置過期時(shí)間的時(shí)候會(huì)失效,建議采用$cookies
以上所述是小編給大家介紹的Angularjs cookie 操作實(shí)例詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
AngularJS ngModel實(shí)現(xiàn)指令與輸入直接的數(shù)據(jù)通信
這篇文章主要介紹了AngularJS ngModel實(shí)現(xiàn)指令與輸入直接的數(shù)據(jù)通信的相關(guān)資料,需要的朋友可以參考下2016-09-09深入理解angular2啟動(dòng)項(xiàng)目步驟
本篇文章主要介紹了深入理解angular2啟動(dòng)步驟 ,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07Angular應(yīng)用里異步打開對(duì)話框技術(shù)詳解
這篇文章主要為大家介紹了Angular應(yīng)用里異步打開對(duì)話框技術(shù)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12angular 組件通信的幾種實(shí)現(xiàn)方式
這篇文章主要介紹了angular 組件通信的幾種實(shí)現(xiàn)方式,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07使用 Github Actions 自動(dòng)部署 Angular 應(yīng)用到 Github Pages的方法
這篇文章主要介紹了使用 Github Actions 自動(dòng)部署 Angular 應(yīng)用到 Github Pages,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07