angularjs操作cookie

路阳华
2023-12-01

angular-cookies.js

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <script src="https://cdn.jsdelivr.net/npm/angular@1.8.2/angular.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/angular-cookies@1.8.2/angular-cookies.js"></script>
</head>
<body>
<div ng-controller="MyController">
  <h3>Cookies</h3>
  <div>
    <div>all cookies: {{ myCookies|json }}</div>
  </div>
  <div>
    <div>mytest: {{ mytest }}</div>
    <div>dataObj: {{ dataObj|json }}</div>
  </div>
</div>

<script>
  // $cookieStore已废弃
  var app = angular.module('myApp', ['ngCookies']);
  app.controller('MyController', ['$scope', '$cookies',
    function ($scope, $cookies) {
      // 移除对应key的cookie
      $cookies.remove('dotobject');
      var dataObj = {
        'aa': '123',
        'b': 2
      };
      $cookies.test1 = 'test1';
      $cookies.put('put1', 'put1 value');
      $cookies.put('put2', 'put2 value');
      var expireDate = new Date();
      expireDate.setDate(expireDate.getDate() + 30);
      // 设置cookie保存30天,默认有效期为session
      $cookies.put('mytest', 'mytest', { 'expires': expireDate });
      $cookies.putObject('dataObj', dataObj);

      $scope.myCookies = $cookies.getAll();
      $scope.mytest = $cookies.get('mytest');
      $scope.dataObj = $cookies.getObject('dataObj')
      
    }])
</script>
</body>
</html>
 类似资料: