使用AngularJS创建cookie

时间:2015-03-18 13:09:45

标签: angularjs cookies setcookie angular-cookies

我尝试使用以下代码设置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';
}]);

3 个答案:

答案 0 :(得分:9)

通过设置$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';
}]);

Source


注意: 请务必在您的HTML中添加<script src="angular-cookies.js">

答案 1 :(得分:4)

您必须在模块中注入ngCookies

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

答案 2 :(得分:2)

模块中缺少ngcookies

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