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

有没有AngularJS的规范方法?


当前回答

供你参考,我用$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>

其他回答

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

下面是一个使用$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");
        };
    }]);

})();

添加angular cookie lib: angular-cookies.js

您可以对相应的控制器使用$cookies或$cookieStore参数

主控制器添加这个注入'ngCookies'

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

在你的控制器中像这样使用cookie:

 app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) { 

//store cookies

 $cookies.putObject('final_total_price', $rootScope.fn_pro_per);

//Get cookies

 $cookies.getObject('final_total_price'); }

最初接受的答案提到了jquery。饼干插件。几个月前,它被重命名为js-cookie,并删除了jQuery依赖项。其中一个原因是为了让它更容易与其他框架集成,比如Angular。

现在,如果你想把js-cookie和angular集成起来,就像这样简单:

module.factory( "cookies", function() {
  return Cookies.noConflict();
});

就是这样。没有jQuery。没有ngCookies。


您还可以创建自定义实例来处理编写方式不同的特定服务器端cookie。以PHP为例,它将服务器端的空格转换为加号+,而不是百分号编码:

module.factory( "phpCookies", function() {
  return Cookies
    .noConflict()
    .withConverter(function( value, name ) {
      return value
            // Decode all characters according to the "encodeURIComponent" spec
            .replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
            // Decode the plus sign to spaces
            .replace(/\+/g, ' ')
    });
});

自定义提供者的用法是这样的:

module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
  this.storeData = function( data ) {
    phpCookies.set( "data", data );
  };
  this.containsStoredData = function() {
    return phpCookies.get( "data" );
  }
}]);

我希望这能对大家有所帮助。

查看详细信息:https://github.com/js-cookie/js-cookie/issues/103

有关如何与服务器端集成的详细文档,请参阅这里:https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md

这就是如何设置和获取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>