Create cookie with AngularJS

☆樱花仙子☆ 提交于 2019-11-27 15:20:04

问题


I tried to use the code below to set cookies:

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

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

I updated to version 1.3.14 of angular cookies, I know there is a breaking change, but how should I write the above code now ?

Running the above code I get this error : Error: $cookies.put is not a function


UPDATE : I have to do this in 2 files:

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';
}]);

回答1:


It happends via setting the $cookies variable:

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

Your version:

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


NOTE: Remember to include <script src="angular-cookies.js"> in your html.




回答2:


You must inject ngCookies in your module:

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



回答3:


Missing ngcookies in your module

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


来源:https://stackoverflow.com/questions/29122989/create-cookie-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!