虽然使用JavaScript创建和获取Cookie很简单,AngularJs还是把它作为一个单独的模块进行了封装,模块名为ngCookies,和前面的教程中做法一样,先引入angular-cookies.js:

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

然后將ngCookies模块注入到我们自定义的模块中:

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

这里我们需要把Cookies读写相关的服务$cookieStore注入到控制器中。通过$cookieStore的get和put方法进行读和写操作。

我们看一个完整的案例:

<!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信息并以对话框的形式弹出。

接下来看一下效果:

AngularJs轻松入门(八)Cookies读写-LMLPHP

05-08 15:51