6

我尝试使用下面的代码来设置 cookie:

angular.module('myApp').controller('myController', ['$scope', '$http','$cookies', function ($scope, $http, $cookies) {

    $scope.setMyCookie = function () {
        $cookies.put('Mykey', 'MyValue');    
    };
    $scope.setMyCookie();
}]);

我更新到 Angular cookie 的 1.3.14 版本,我知道有一个重大更改,但是我现在应该如何编写上面的代码?

运行上面的代码我得到这个错误:Error: $cookies.put is not a function


更新:我必须在 2 个文件中执行此操作:

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

app.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {

}]);

angular.module('myApp', ['ngCookies']).controller('cookiesExample', ['$cookies', function ($cookies) {
    // Retrieving a cookie
    var favoriteCookie = $cookies.myFavorite;
    // Setting a cookie
    $cookies.myFavorite = 'oatmeal';
}]);
4

3 回答 3

10

它通过设置$cookies变量发生:

angular.module('cookiesExample', ['ngCookies'])
.controller('ExampleController', ['$cookies', function($cookies) {
  // Retrieving a cookie
  var favoriteCookie = $cookies.myFavorite;
  // Setting a cookie
  $cookies.myFavorite = 'oatmeal';
}]);

你的版本:

angular.module('myApp', ['ngCookies'])
.controller('myController', ['$scope', '$http','$cookies', function ($scope, $http, $cookies) {

  // Retrieving a cookie
  var favoriteCookie = $cookies.myFavorite;
  // Setting a cookie
  $cookies.myFavorite = 'oatmeal';
}]);

资源


注意: 请记住包含<script src="angular-cookies.js">在您的 html 中。

于 2015-03-18T13:14:12.730 回答
4

你必须注入ngCookies你的模块:

angular.module('myApp', ['ngCookies'])
于 2015-03-18T13:13:06.933 回答
2

ngcookies您的模块中缺少

angular.module('myApp', ['ngCookies'])
于 2016-03-03T12:24:52.537 回答