【问题标题】:How to store and get a array cookie with Angular如何使用 Angular 存储和获取数组 cookie
【发布时间】:2017-06-22 05:16:00
【问题描述】:

当用户点击 GO 按钮时,我需要将值推送到数组中并存储在 cookie 中。

如果值大于 10,我需要删除数组中第一个添加的项目并更新 cookie,显示在前端。

但我尝试了多种方法,有时我得到的值有时不是,代码无法始终如一地工作。

请在代码下方找到

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

在前端:

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

【问题讨论】:

标签: javascript jquery angularjs cookies setcookie


【解决方案1】:

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

【讨论】:

  • 初始加载我的页面出现“长度未定义”错误
  • 代码不工作,因为我使用 Angular 1.4 以上版本
  • @CodeMan 我已经修改了代码以适应 angular 1.4
猜你喜欢
  • 2016-08-12
  • 2017-06-22
  • 1970-01-01
  • 2012-02-20
  • 2018-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
相关资源
最近更新 更多