如何使用angularjs在本地存储中保存json响应?

时间:2014-08-20 06:17:36

标签: json angularjs

我有api返回json响应,我想在localstorage中存储json响应,以便在我使用angularjs的另一个html页面中使用该响应。

这是我的代码返回json响应....

QAApp.controller('SearchCtrl', function ($scope, $http, $location) {

  $scope.search = function (searchtag) {
           var request = $http({
                          method: 'GET', 
                          url: server + 'api/question/tagged/' + searchtag,
                        });
                request.success(function(data, status, headers, config) {
                console.log(data);
                $scope.qa = data;
            });

        }
  }); 

请告诉我如何储存它......

6 个答案:

答案 0 :(得分:18)

在您的request.success()上,使用

window.localStorage['storageName'] = angular.toJson(data);

然后您可以通过

访问localstorage中的数据
var accessData = window.localStorage['storageName'];

答案 1 :(得分:5)

我想建议这个,因为我使用它并且它运行稳定https://github.com/gsklee/ngStorage

下载并将其附加到项目后,您应将其添加为依赖项

    QAApp.controller('SearchCtrl', function ($scope, $http, $location,$localStorage) {

      $scope.search = function (searchtag) {
               var request = $http({
                              method: 'GET', 
                              url: server + 'api/question/tagged/' + searchtag,
                            });
                    request.success(function(data, status, headers, config) {
                    $localStorage.qa = datal
                    $scope.qa = data;
                });



  }
  }); 

答案 2 :(得分:3)

我建议在GitHub上使用angular-local-storage模块。

答案 3 :(得分:3)

$scope.Save = angular.toJson(data); //Save to storage
sessionStorage.setItem('blablabla',$scope.Save);
localStorage.setItem('blablabla', $scope.Save); 

$scope.DataFromJson = JSON.parse(sessionStorage["blablabla"]); //Get from storage
$scope.DataFromJson = JSON.parse(localStorage["blablabla"]);

答案 4 :(得分:2)

/ *从localStorage * /

中检索json
var user = angular.fromJson($window.localStorage['md-user']);

/ *将json存储在loacalStorage * /

$window.localStorage['md-user'] = angular.toJson(user);

答案 5 :(得分:0)

要存储

w

要检索

$scope.storeItem = function() {
 sessionStorage.setItem('item', angular.toJson($scope.selectedItem));
}