0

I feel like tons of people do this all the time, and yet I have been unsuccessful in finding similar examples.

I am getting data from the backend using angularJS ($http.post) to a controller in a javascript file, and presenting it in one html. The data is received after sending a search query from that html. Now, I want to "export" that data to another JS file and to present some of it again, in a new html. The problem is that I have access to that data only through the Search Controller during the searching session, and I probably need to store it somehow or send it to another controller/ JS file.

Unfortunately, I cannot use $cookies. Also, I am trying to avoid sending a new request through the server if I don't have to.

I have read a some about services in angular, however, I am new to angular (and UI in general), and for some reason was unable to implement this for my specific case.

Here is an example of the relevant controller, after getting a search request from the html page:

app.controller('SearchCtrl', ['$scope', '$http',
      function($scope, $http) {
        $scope.searchJSON = {
          searchToken: [],
          searchOption: []
     
        $scope.sendSearch = function() {
//preparing JSON to send request to server
          $scope.searchJSON["searchToken"] = this.search.searchToken;
          $scope.searchJSON["searchOption"] = this.search.searchOption;
          var json = $scope.searchJSON;
//sending and getting response (JSON object)
          $http.post("http://some_host", json)
            .success(function(response) {
              
              $scope.collections = response.searchResults;
            });
        };
}]);

So the data I am interested in passing on to another JS file is in $scope.collections , which is a JSON file (I don't want use the same JS file for both html pages, so was hoping to call that data from a new controller in a new JS file).

Will appreciate any answers, leads, or similar examples from the web. Thank folks!

GuyTal
  • 207
  • 5
  • 17
  • Are you hoping to keep the results after a page reload? Or is the "new JS file" a controller on another route or something like that – AndyPerlitch Jan 28 '16 at 18:01
  • I only want to keep the results in order to present it on the new page @AndyPerlitch . I don't mind losing them after session ends/browser is closed. In fact, I definitely cannot have it stored for long term anywhere on the client's side. – GuyTal Jan 28 '16 at 18:05
  • Got it. I posted my answer below. Hope it helps – AndyPerlitch Jan 28 '16 at 18:09

4 Answers4

0

One possible way to solve this is by using sessionStorage/localStorage on $window. You can store your data there and after redirecting to another file, you can use it by invoking.

tanmay
  • 7,761
  • 2
  • 19
  • 38
0

You are right to bring up services because that is how I would personally implement this. Create a service to handle the search request and also to store the result via promises:

angular.module('yourModule')
  .factory('searchService', function($http, $q) {

    var searchService = {

      resultsPromise: null,

      sendSearch: function(token, option) {
        var dfd = $q.defer();
        var json = {
          searchToken: token,
          searchOption: option
        };
        $http.post("http://some_host", json).then(
          function(response) {
            // resolve your deferred
            dfd.resolve(response.data);
          },
          dfd.reject
        );
        this.resultsPromise = dfd.promise;
        return dfd.promise;
      }

    };

    return searchService;

   });

Then in your current controller, just do:

app.controller('SearchCtrl', ['$scope', 'searchService',
  function($scope, searchService) {
    $scope.searchJSON = {
      searchToken: [],
      searchOption: []

    $scope.sendSearch = function() {
      searchService.sendSearch($scope.searchJSON.searchToken, $scope.searchJSON.searchOption);
    };

Then in your other file, simply look at the currentResults of the same service:

app.controller('OtherCtrl', function($scope, searchService) {
  if (searchService.resultsPromise) {
    searchService.resultsPromise.then(function(results) {
      $scope.results = results;
    });
  }
});
AndyPerlitch
  • 4,539
  • 5
  • 28
  • 43
  • Thank you @AndyPerlitch, I will try to implement this. Also, what about my current controller, 'SearchCtrl'? I still need to present the data in the current html as well, as search results. I need to add the content of 'OtherCtrl' to the bottom of 'SearchCtrl to retrieve the results from the service right? – GuyTal Jan 28 '16 at 18:42
  • Simply use `searchService.resultsPromise` in the SearchCtrl – AndyPerlitch Jan 30 '16 at 01:17
0

You can ditch the $http service and use $resource instead. From there you can use $cacheFactory as seen in this post: How to cache an http get service in angularjs

Community
  • 1
  • 1
Jean-François Beaulieu
  • 4,305
  • 22
  • 74
  • 107
  • can you please elaborate with an answer? I tried your suggestion using that link, but doesn't seem to work for some reason. – GuyTal Jan 30 '16 at 01:55
0

An alternative solution is http://jmdobry.github.io/angular-cache/ which works well with ngResource and can also easily be configured to sync to localStorage, so requests don't need to be re-done after page refresh.

`$resource('my/kewl/url/:key', { key: '@key' }, {
'get': { method: 'GET', 
       cache: $angularCacheFactory('MyKewlResourceCache', { 
                                      storageMode: 'localStorage' })
     }
 });`
Neeraj Goswami
  • 101
  • 2
  • 6