一尘不染

使用AngularJS创建cookie

angularjs

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

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

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

我已将角度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';
}]);

阅读 197

收藏
2020-07-04

共1个答案

一尘不染

通过设置$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中。

2020-07-04