AngularJS-cookie讀寫

雖然使用JavaScript建立和獲取Cookie很簡單,AngularJs仍是把它做爲一個單獨的模塊進行了封裝,模塊名爲ngCookies,和前面的教程中作法同樣,先引入angular-cookies.js:javascript

<script type="text/javascript" src="angular-1.3.0.14/angular-cookies.js"></script>

而後將ngCookies模塊注入到咱們自定義的模塊中:html

var cookiesMod = angular.module("cookiesMod",['ngCookies']);

這裏咱們須要把Cookies讀寫相關的服務$cookieStore注入到控制器中。經過$cookieStore的get和put方法進行讀和寫操做。java

咱們看一個完整的案例:cookie

<!DOCTYPE html>
<html ng-app="cookiesMod">
<head lang="en">
    <meta charset="UTF-8">
    <script type="text/javascript" src="angular-1.3.0.14/angular.js"></script>
    <script type="text/javascript" src="angular-1.3.0.14/angular-cookies.js"></script>
    <title>tutorial08</title>
</head>
<body ng-controller="CookiesController" ng-init="init()">
<button ng-click="getInfo()">獲取Cookies信息</button>
</body>
<script>
    var cookiesMod = angular.module("cookiesMod",['ngCookies']);
    cookiesMod.controller("CookiesController",function($scope,$log,$cookieStore){
        $scope.init = function()
        {
            $log.info("init functionn");
            $cookieStore.put("person",{name:"Rongbo_J",age:23});
        }

        $scope.getInfo = function()
        {
            var person = $cookieStore.get("person") ;
            alert("name : " + person.name +" , "+ "age : " + person.age);
        }

    });
</script>
</html>

在頁面加載時咱們寫入Cookies信息,cookie名爲person,值爲{name:"Rongbo_J",age:23},點擊按鈕獲取cookie信息並以對話框的形式彈出。 
接下來看一下效果:app

這裏寫圖片描述

相關文章
相關標籤/搜索