无法在页面加载时从cookie检索数组

时间:2016-09-10 13:15:23

标签: angularjs cookies angularjs-ng-repeat

不确定我的问题的标题是否正确, 我将搜索的输入存储在一个数组中,并将该数组放在一个cookie中。当页面刷新时,我使用init函数初始化arr,用于与cookie中存储的arr重复使用。但我面临错误:

nameapp.controller('NameCtrl',
        function($scope,$http,$window, $cookieStore,$sessionStorage,$cookies ,myService){
    // code for storing array in the cookie 

              $http.get('https://finance.google.com/finance/info?client=w&q='+$scope.stock).success(function(data,status)
            {
               $scope.share=JSON.parse(data.substring(5,data.length-2));
                $scope.arr.push($scope.share);----> error here 
                console.log(status+"-------"+JSON.stringify($scope.arr));
            }).error( function ()
        {
        alert("fail");
        })
    }
        ;

$scope.init = function () {
    var s =$cookies.get("arr");
       $scope.arr=$cookies.get("arr") ;
    console.log("JSON.stringify($cookies.get('arr'))="+s);
}
    }
    );
    </script>
</head>


<body ng-controller="NameCtrl" ng-init="init()">

<form ng-submit="finddet()">
    <input type="text" ng-model="stock">
    <input type="submit">
</form>

<ul>
    <li ng-repeat="name in names">{{name}}</li>

    <li ng-repeat="sr in arr track by $index"> value : {{sr.l_cur}} <a href='#' ng-click="removename(sr)"> remove </a></li> 
</ul>
</body>
</html>

on ---&gt;行,控制台错误:

TypeError: $scope.arr.push is not a function
    at (index):99

不确定如何使用页面加载中的cookie初始化ng repeat数组。请修改。

1 个答案:

答案 0 :(得分:0)

Cookie是String,不能是另一个对象。因此,在保存之前将数组转换为json,并在加载时恢复为对象

相关问题