Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create cookie with AngularJS

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';
}]);
like image 365
Kris-I Avatar asked Mar 18 '15 13:03

Kris-I


People also ask

How to create cookies in AngularJS?

Angular has inbuilt directives named as ngCookies. Writing Cookies: The WriteCookie function of the controller gets called When the Write Cookie Button is clicked. The WriteCookie function saves the input box value as cookies, using the $cookieStore service of the ngCookies module.

What is ngCookies?

The ngCookies module provides a convenient wrapper for reading and writing browser cookies.

What is AngularJS used for?

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML's syntax to express your application's components clearly and succinctly. AngularJS's data binding and dependency injection eliminate much of the code you would otherwise have to write.


3 Answers

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.

like image 50
Piotr Dajlido Avatar answered Oct 15 '22 11:10

Piotr Dajlido


You must inject ngCookies in your module:

angular.module('myApp', ['ngCookies'])
like image 34
valverde93 Avatar answered Oct 15 '22 11:10

valverde93


Missing ngcookies in your module

angular.module('myApp', ['ngCookies'])
like image 2
Pulithevan S Avatar answered Oct 15 '22 10:10

Pulithevan S