如何在AngularJS中设置、获取和清除cookies

如何在AngularJS中设置、获取和清除cookies

在这篇文章中,我们将看到如何在AngularJS中设置、获取和清除Cookie,同时通过实现了解基本用法。在AngularJS中,我们需要使用angular-cookies.js来设置、获取和清除cookies。你可以使用实时CDN链接来实现:https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-cookies.js

我们需要在控制器中加入$cookies,它必须有Get、Set和Clear方法来分别获取、设置和清除cookies。Angular有内置的指令,名为ngCookies。

写入Cookie:控制器的WriteCookie函数在Write Cookie按钮被点击时被调用。WriteCookie函数将输入框的值保存为cookie,使用ngCookies模块的$cookieStore服务。$cookieStore放函数有两个参数

  • Name (Key)
  • Value

语法:

$scope.SetCookies = function () {
    $cookies.put("username", $scope.username);
};

读取Cookie:当读取Cookie按钮被点击时,控制器的ReadCookie函数被调用。ReadCookie函数使用ngCookies模块的$cookieStore服务来获取Cookie的值。$cookieStore获取函数有一个参数:

  • Name (Key)

语法:

$scope.GetCookies = function () {
    $window.alert($cookies.get('username'));
};

移除Cookie:当移除Cookie按钮被点击时,控制器的RemoveCookie函数被调用。RemoveCookie函数使用ngCookies模块的$cookieStore服务来移除Cookie。$cookieStore删除函数有一个参数:

  • Name (Key)

语法:

$scope.ClearCookies = function () {
    $cookies.remove('username');
};

例子:这个例子说明了在AngularJS中设置、获取和清除cookies。

<!DOCTYPE html>
<html>
  
<head>
    <title>
        A Simple example of Get, Set
        and Clear Cookie in AngularJS
    </title>
    <script type="text/javascript"
        src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js">
    </script>
    <script type="text/javascript"
        src=
"https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-cookies.js">
    </script>
</head>
  
<body style="text-align: center">
    <h1 style="color: green">GeeksforGeeks</h1>
    <h2>set, get and clear cookies in AngularJs</h2>
  
    <script type="text/javascript">
        var app = angular.module('MyApp', ['ngCookies']);
  
        app.controller('CookiesController', 
        function (scope,window, cookies) {
            scope.SetCookies = function () {
                cookies.put('username',scope.username);
            };
  
            scope.GetCookies = function () {
                window.alert(cookies.get('username'));
            };
  
            scope.ClearCookies = function () {
                $cookies.remove('username');
            };
        });
    </script>
    <div ng-app="MyApp" ng-controller="CookiesController">
        Username:
        <input type="text" ng-model="username" />
        <br />
        <br />
        <input type="button" 
               value="Set Cookies" 
               ng-click="SetCookies()" />
  
        <input type="button" 
               value="Get Cookies" 
               ng-click="GetCookies()" />
  
        <input type="button" 
               value="Clear Cookies" 
               ng-click="ClearCookies()" />
    </div>
</body>
</html>

输出:

如何在AngularJS中设置、获取和清除cookies?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程