[轉]AngularJS Cookies Example

來源:互聯網
上載者:User

標籤:

AngularJS Cookies Example

AngularJS 提供了很好的 $cookie 和 $cookieStore API 用來處理 cookies 。 

這兩個服務都能夠很好的發揮HTML5 cookies,當HTML5 API可用時瀏覽器會選擇使用HTML5提供的API,如果不可用則預設選擇document.cookies。無論那種方式,你都可以選擇使用相同的API來進行工作。

Step 1 - include cookies module

第一步載入JS檔案,並且依賴 cookie module

<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script><script src="http://code.angularjs.org/1.2.9/angular-cookies.min.js"></script>

建立 angular module

var DemoApp = angular.module( ‘DemoApp‘, [‘ngCookies‘] ).config( demoConfig );
Step 2 - Inject into controller

將cookie module 注入到 controller 中

DemoApp.controller(‘DemoController‘, function($cookieStore, $scope, $location, $routeParams, $http , $timeout ){ .. body here .. })
Step 3 - Using the $cookieStore

現在可以使用 ‘put’ 、 ‘get’ 、‘remove’ 方法操作 cookie , $cookieStore 可以直接儲存物件到cookie中,它會使用angularjs 的 toJson/fromJson 自動序列化和還原序列化

$cookieStore.put("name","my name");$cookieStore.get("name") == "my name";$cookieStore.remove("name");$cookieStore.put("persion", {            name: "my name",            age: 18});scope.person = $cookieStore.get("persion");
Step 4 - Using the $cookie
DemoApp.controller(‘DemoController‘, function ($cookies, $scope) {        $cookies.myFavorite = ‘oatmeal haha‘;})  
Step 5 Demo Code
  • $cookieStore Demo Code
  • $cookies Demo Code

[轉]AngularJS Cookies Example

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.