简体   繁体   中英

How to store and get a array cookie with Angular

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

JS:

$scope.lastorder = $cookies['lastorder'];

$scope.cookiefunction=function(val) {
                /*
                $scope.lastorder.push(val);
                if($scope.lastorder.length > 4){
                        $scope.lastorder.shift();
                }
                $cookies.putObject('lastorder',$scope.lastorder);*/


                $cookies['lastorder']={'productname':val};
                $scope.lastorder = $cookies['lastorder'];
                if($scope.lastorder.length > 4){
                        $scope.lastorder.shift();
                }
                //$cookies['lastorder']={$scope.lastorder};
                $scope.lastorder = $cookies['lastorder'];
        };

in Frond end:

li ng-repeat="x in lastorder">{{x.productname}}

Plunkr: Click here

  var DemoApp = angular.module('DemoApp', ['ngCookies']);

    DemoApp.controller('DemoController', function ($cookies, $scope, $log) {
      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}); 
        $cookies.putObject(cookieName, $scope.orderList);
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM