Search code examples
javascriptjqueryangularjscookiessetcookie

How to store and get a array values in cookie with Angular version 1.5


I need to push value in array and stored in cookies when user click on GO button.

if value is more than 10 i need to remove the first added item in the array and updated cookies , displayed in front end.

but i'm tried multiple ways some time i am getting values sometimes not , the code is not consistently working.

please find below the code

var cookieName = 'orderList';
$scope.orderList = $cookies.getObject(cookieName) || [];
$scope.saveCookie = function (val) {
    if ($scope.orderList.length >= 10) {
      $scope.orderList.shift();
    }

    $scope.orderList.push({productName: val}); 
    $scope.orderList = $cookies.putObject(cookieName,$scope.orderList);
  }

Note : I am using angular 1.5 and cookie 1.5 version .and i am getting console error .

http://plnkr.co/edit/K17uJv72U2ytG6JHZBtn?p=preview


Solution

  • You didn't realize one thing. The error only appears when you click the button the second time. The reason why you're getting this error is the last line in your code-

    $scope.orderList = $cookies.putObject(cookieName,$scope.orderList);

    when you replace it with -

    console.log(typeof $cookies.putObject(cookieName,$scope.orderList));

    you'll get undefined in the console. And that is the catch. When the function runs the second time, it is evaluating length of undefined, and hence, the error.

    Just replace the line with $cookies.putObject(cookieName,$scope.orderList), because your $scope.orderList is already equal to the array with the new value pushed.

    EDIT: Updated Code

    var cookieName = 'orderList';
    $scope.saveCookie = function (val) {
        $scope.orderList = $cookies.getObject(cookieName) || [];
        if ($scope.orderList.length >= 10) {
          $scope.orderList.shift();
        }
    
        $scope.orderList.push({productName: val}); 
        $cookies.putObject(cookieName,$scope.orderList);
    }
    

    I brought the definition of $scope.orderList inside the function, since, in case the value of it is lost, it will reevaluate on each button click. Its not crucial in all cases. You might keep it out of the function, depending on your application flow.