Angular Storing数组到Cookie中

时间:2017-03-06 13:12:48

标签: angularjs

我有一个下面的函数可以正常工作并将信息传递到cookieStore并从中检索而不会出现问题

country_footer_url = reverse('country_reference')  # or use a string containing your url


class Table(tables.Table):
    country = tables.Column(
        footer=format_html('<a href="{}">country reference</a>', country_footer_url
    )

但是,当我尝试使用以下verufyGuess函数注入索引而没有作为参数进入函数时,它无法放入cookieStore

$ scope.verifyGuess = function(Index,no){

            $scope.num = 0
            $scope.nums = []

            $scope.increment = function () {
                $scope.num++
            }
            $scope.$watch('num', function () {
                $scope.nums.push($scope.num)
            })
            $scope.storeProductsInCookie=function(){
                $cookieStore.put("invoices",$scope.nums)
            };
            $scope.getProductsInCookie=function(){
                console.log(  $cookieStore.get("invoices",$scope.nums));
            }

1 个答案:

答案 0 :(得分:0)

$cookieStore已弃用:(自v1.4.0开始) 请改用$cookies服务。

$scope.nums是一个字符串数组。所以$cookieStore将它们存储为字符串(cookies只支持存储的字符串)。

在第二种情况下,$scope.newVotes是一个对象数组。饼干不会存储物品。

您必须使用$cookieStore.put("invoices", JSON.stringify($scope.newVotes))

 <!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.12/angular-cookies.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <script>
    var app = angular.module('plunker', ['ngCookies']);

    app.controller('MainCtrl', function($scope, $cookies) {

      $scope.votes = {};
      $scope.newVotes = []
      var Index = 0;
      $scope.votes[Index] = $scope.votes[Index] || 0;
      $scope.votes[Index] += 10;


      $scope.newVotes.push($scope.votes)

      $scope.storeProductsInCookie = function() {
        $cookies.put("invoices", JSON.stringify($scope.newVotes))
      };
      $scope.getProductsInCookie = function() {
        console.log($cookies.get("invoices"));
      }

      $scope.storeProductsInCookie();
      $scope.getProductsInCookie();

    });
  </script>
</body>


</html>