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

Ani*_*hta 14 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;
            });

        }
  }); 
Run Code Online (Sandbox Code Playgroud)

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

Raj*_*lal 19

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

window.localStorage['storageName'] = angular.toJson(data);
Run Code Online (Sandbox Code Playgroud)

然后,您可以访问localstorage中的数据

var accessData = window.localStorage['storageName'];
Run Code Online (Sandbox Code Playgroud)


Nar*_*yan 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;
                });



  }
  }); 
Run Code Online (Sandbox Code Playgroud)