AngularJs Browser Back Button: Returns to the previous spot on the page

I am 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 an item, he goes to the detailed view for that item. If they click the back button in the browser, angular returns them to the list, but it returns to the top of the list.

Usually on a simple HTML page, if you scroll down the page, click on the link and go to another page, if you click the "Back" button in the browser, it will return you back to the scroll point where you were on this page. This is very useful if you are viewing a list of items.

Is there a way for Angular to mimic this behavior so that when using the back button, the user returns to the list and to the same scroll location?

+4
source share
1 answer

It looks like you want to use the HTML history API, for example window.history.pushState()and window.history.popState(). It also looks like you want to use browser scroll.

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

, AngularJS, jQuery pushState(), URL- ( # ), popState(), - , , "".

$(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);
}
0

All Articles