AngularJS访问cookie的方式是什么?我看到了对cookie的服务和模块的引用,但没有示例。

有没有AngularJS的规范方法?


当前回答

This answer has been updated to reflect latest stable angularjs version. One important note is that $cookieStore is a thin wrapper surrounding $cookies. They are pretty much the same in that they only work with session cookies. Although, this answers the original question, there are other solutions you may wish to consider such as using localstorage, or jquery.cookie plugin (which would give you more fine-grained control and do serverside cookies. Of course doing so in angularjs means you probably would want to wrap them in a service and use $scope.apply to notify angular of changes to models (in some cases).

另一个注意事项是,在提取数据时,两者之间有轻微的区别,这取决于您是使用$cookie存储值还是使用$cookieStore。当然,你真的想要使用其中一个。

除了添加对js文件的引用,你还需要将ngCookies注入到你的应用定义中,例如:

angular.module('myApp', ['ngCookies']);

然后你就可以出发了。

下面是一个函数最小化的例子,其中我展示了cookie estore是一个围绕cookie的薄包装器:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
   <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="MyController">

  <h3>Cookies</h3>
  <pre>{{usingCookies|json}}</pre>
  <h3>Cookie Store</h3>
  <pre>{{usingCookieStore|json}}</pre>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
  <script>
    angular.module('myApp', ['ngCookies']);
    app.controller('MyController',['$scope','$cookies','$cookieStore', 
                       function($scope,$cookies,$cookieStore) {
      var someSessionObj = { 'innerObj' : 'somesessioncookievalue'};

    $cookies.dotobject = someSessionObj;
    $scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };

    $cookieStore.put('obj', someSessionObj);
    $scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
    }
  </script>

</body>
</html>

步骤如下:

包括angular.js 包括angular-cookies.js 注入ngCookies到你的app模块中(并确保你在ng-app属性中引用了该模块) 添加一个$cookies或$cookieStore参数到控制器 使用点(.)操作符将cookie作为成员变量访问 ——或—— 使用put/get方法访问cookestore

其他回答

This answer has been updated to reflect latest stable angularjs version. One important note is that $cookieStore is a thin wrapper surrounding $cookies. They are pretty much the same in that they only work with session cookies. Although, this answers the original question, there are other solutions you may wish to consider such as using localstorage, or jquery.cookie plugin (which would give you more fine-grained control and do serverside cookies. Of course doing so in angularjs means you probably would want to wrap them in a service and use $scope.apply to notify angular of changes to models (in some cases).

另一个注意事项是,在提取数据时,两者之间有轻微的区别,这取决于您是使用$cookie存储值还是使用$cookieStore。当然,你真的想要使用其中一个。

除了添加对js文件的引用,你还需要将ngCookies注入到你的应用定义中,例如:

angular.module('myApp', ['ngCookies']);

然后你就可以出发了。

下面是一个函数最小化的例子,其中我展示了cookie estore是一个围绕cookie的薄包装器:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
   <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
</head>
<body ng-controller="MyController">

  <h3>Cookies</h3>
  <pre>{{usingCookies|json}}</pre>
  <h3>Cookie Store</h3>
  <pre>{{usingCookieStore|json}}</pre>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-cookies.js"></script>
  <script>
    angular.module('myApp', ['ngCookies']);
    app.controller('MyController',['$scope','$cookies','$cookieStore', 
                       function($scope,$cookies,$cookieStore) {
      var someSessionObj = { 'innerObj' : 'somesessioncookievalue'};

    $cookies.dotobject = someSessionObj;
    $scope.usingCookies = { 'cookies.dotobject' : $cookies.dotobject, "cookieStore.get" : $cookieStore.get('dotobject') };

    $cookieStore.put('obj', someSessionObj);
    $scope.usingCookieStore = { "cookieStore.get" : $cookieStore.get('obj'), 'cookies.dotobject' : $cookies.obj, };
    }
  </script>

</body>
</html>

步骤如下:

包括angular.js 包括angular-cookies.js 注入ngCookies到你的app模块中(并确保你在ng-app属性中引用了该模块) 添加一个$cookies或$cookieStore参数到控制器 使用点(.)操作符将cookie作为成员变量访问 ——或—— 使用put/get方法访问cookestore

这就是如何设置和获取cookie值。这就是我找到这个问题的初衷。

注意,我们使用$cookieStore而不是$cookies

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
  <script src="http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js"></script>
  <script>
    angular.module('myApp', ['ngCookies']);
    function CookieCtrl($scope, $cookieStore) {
      $scope.lastVal = $cookieStore.get('tab');

      $scope.changeTab = function(tabName){
          $scope.lastVal = tabName;
          $cookieStore.put('tab', tabName);
      };
    }
  </script>
</head>
<body ng-controller="CookieCtrl">
    <!-- ... -->
</body>
</html>

下面是一个使用$cookies的简单示例。单击按钮后,cookie将被保存,重新加载页面后,cookie将被恢复。

app.html:

<html ng-app="app">
<head>
    <meta charset="utf-8" />
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-cookies.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="appController as vm">

    <input type="text" ng-model="vm.food" placeholder="Enter food" />

    <p>My favorite food is {{vm.food}}.</p>

    <p>Open new window, then press Back button.</p>
    <button ng-click="vm.openUrl()">Open</button>
</body>
</html>

app.js:

(function () {
    "use strict";

    angular.module('app', ['ngCookies'])
    .controller('appController', ['$cookies', '$window', function ($cookies, $window) {
        var vm = this;

        //get cookie
        vm.food = $cookies.get('myFavorite');

        vm.openUrl = function () {
            //save cookie
            $cookies.put('myFavorite', vm.food);
            $window.open("http://www.google.com", "_self");
        };
    }]);

})();

AngularJS提供了ngCookies模块和$cookieStore服务来使用浏览器cookie。

我们需要添加angular-cookies.min.js文件来使用cookie特性。

下面是AngularJS Cookie的一些方法。

(关键);//该方法返回给定cookie key的值。 getObject(关键);//该方法返回给定对象的反序列化值 饼干的关键。 getAll ();//该方法返回一个键值对象 饼干。 Put (key, value, [options]);//该方法设置一个给定的值 饼干的关键。 删除(关键,[选项]);//此方法删除给定的cookie。

例子

Html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>

JavaScript

var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);

我已经参考了http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php。

供你参考,我用$cookieStore、两个控制器、$rootScope和AngularjS 1.0.6组合了一个JSFiddle。它在JSFifddle的http://jsfiddle.net/krimple/9dSb2/作为一个基地,如果你搞砸了这个…

它的要点是:

Javascript

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

myApp.controller('CookieCtrl', function ($scope, $rootScope, $cookieStore) {
    $scope.bump = function () {
        var lastVal = $cookieStore.get('lastValue');
        if (!lastVal) {
            $rootScope.lastVal = 1;
        } else {
            $rootScope.lastVal = lastVal + 1;
        }
        $cookieStore.put('lastValue', $rootScope.lastVal);
    }
});

myApp.controller('ShowerCtrl', function () {
});

HTML

<div ng-app="myApp">
    <div id="lastVal" ng-controller="ShowerCtrl">{{ lastVal }}</div>
    <div id="button-holder" ng-controller="CookieCtrl">
        <button ng-click="bump()">Bump!</button>
    </div>
</div>