'AngularJs Browser Back Button: Go Back to Previous Spot on Page

I'm using Angular for a single page application. Sometimes I have a longer list of items. When the user scrolls down the page and clicks on the item, they go to a detailed view for that item. If they hit the back button on the browser angular takes them back to the list, but it goes back to the top of the list.

Normally on a simple HTML page, if you scroll down a page, and click on a link and go to another page if you hit the back button on the browser, it takes you right back to the scroll location where you were on that page. This is very helpful if you're going through a list of items.

Is there a way to have Angular mimic that behavior so that using the back button will take the user back to the list and the same scroll location?



Solution 1:[1]

It sounds like you want to make use of the HTML history API such as window.history.pushState() and window.history.popState(). It also sounds like you want to use browser scrolling.

A quick google search found me this documentation about $location and this documentation about scrolling from the AngularJS docs.

I don't know how to do this in AngularJS, but in jQuery you can use pushState() to add a specific url to the browser history (that might be a # on your same page) and then you can add a popState() handler that will do something other than refresh the page when the user clicks the back button.

For example

$(document).on('load',function(){
 window.history.replaceState({element: {positionY: 0}},"load",location.pathname);
});

$(mylink).click(function(evt){
 // something like: window.history.pushState(evt.target);
});

// this occurs when the user clicks the back button
$(document).on("popstate", function(evt) {
 evt.preventDefault(); // prevents page refresh
 var state = evt.originalEvent.state;
 window.scrollTo(0,state.element.positionY);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1