Search code examples
javascriptangularjscookiesangular-local-storage

Why aren't $cookies and $localStorage working together?


So I am trying to use angular cookies and local storage together, I am not sure why cookies are working the way they are. Basically, the console.log(theInternet) portion types out to the log that it is undefined, when clearly in the put, it's value is 12.

<body ng-app="app" ng-controller="Ctrl">
  <div ng-controller="internet-test-controller">
    <p>hi</p>
  </br>
  </br>
  <button ng-click="$storage.counter = $storage.counter + 1">{{$storage.counter}}</button>
  <div ng-click="$storage.money = $storage.money + 1">{{$storage.money}}</div>
  </div>
</body>

<script>
var the_app = angular.module('app', ['ngStorage', 'ngCookies'])
the_app.controller('Ctrl', function ($scope, $localStorage, $cookies){
    $scope.$storage = $localStorage.$default({
      counter: 1, 
      money: $cookies.get('123abc')
    });

});
the_app.controller('internet-test-controller', ['$cookies', function($cookies) {
    var theInternet = $cookies.get('123abc');
    $cookies.put('123abc', 12);
    console.log(theInternet);
}]);
</script>

Solution

  • the_app.controller('internet-test-controller', ['$cookies', function($cookies) {
        var theInternet = $cookies.get('123abc');
        $cookies.put('123abc', 12);
        console.log(theInternet);
    }]);
    

    You're reading the (empty) cookie, then storing a value of 12 in it, then logging the original (empty) variable.

    The second time you trigger internet-test-controller, you'll get 12 (because it will start by reading the (not empty) cookie into theInternet.

    Incidentally it's rarely useful or necessary to use both localStorage and cookies -- they serve the same purpose. If you're already depending on localStorage there's no need to use cookies at all.