Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS routing. Save and restore state on back button

I'm trying to figure out the best way to implement the following scenario using AngularJs routing:

  1. Users have a list of items with search capability (e.g. movies).

  2. Users can search and select item, click on it and view details in a separate view.

  3. Once they finish viewing the item they can click browser back button and return to previous list with restored search options to continue viewing the list.

Default ngRoute doesn't provide any state concept and this has to be implemented separately (I wonder what is the best solution here)

Use ui-router. I've never worked with it and I wonder if it provides such functionality out-of-the-box

like image 636
lostaman Avatar asked May 29 '26 03:05

lostaman


1 Answers

For the back button to go back to the same state where the page was in your search screen save the state of search parameters, pagination etc in the URL:

 $location.search({"searchTerm": "jaws", "genre": "fishy", page: 3});

This will add ?searchTerm=jaws&genre=fishy&page=3 to you URL and reload controller. At the start of controller set variables from URL thus:

 var searchTerm = $location.search().searchTerm;
 var genre = $location.search().genre;
 var page =  $location.search().page;
 SearchService.search(searchTerm, genre, page, function(data){
    $scope.results = data;
 });

Now when they click off to the result the back button will work as normal and reload the controller and with the parameters.

If you don't want the browser history to have every action taken in the search screen and only want the last state recorded in the history use replace:

 $location.search({"searchTerm": "jaws", "genre": "fishy", page: 3}).replace();

Now the history will have just a single entry for the search screen regardless of the history of options chosen.

like image 136
DavidC Avatar answered May 31 '26 22:05

DavidC