Tom O'Brien
Tom O'Brien

Reputation: 1831

Angularjs - Back button needs to be clicked twice after using $anchorScroll

I am using $anchorScroll to move the scroll bar on a page to a particular position. In my case, when I click on a link to an episode from a search results page, I want to open the podcast page which contains that episode and scroll down to where that particular episode is and play it. The podcast page can also be loaded normally and not need any scrolling or playing of episodes.

The code to do the positioning is:

$anchorScroll.yOffset = 70;
$location.hash("episode12345");
$anchorScroll();

I am also using $routeProvider to move to the podcast page like so:

.when("/podcasts/:podcast_name", {
    templateUrl: "podcast.html",
    controller: "PodcastController"
})

The problem occurs when, after loading the podcast page and scrolling to the desired episode location, i want to go back to the search results by hitting the browser back button. Unfortunately it needs to be clicked back twice, because the first back click only takes me to the top of the page i am at.

Eg. This is the page url for the episode location:

http://localhost:8080/podcasts/Podcast1#16 

This is the page url after first click:

http://localhost:8080/podcasts/Podcast1#16

After the 2nd click I can go back to my search page where I originally came from for example:

http://localhost:8080/results

When the page initially loads, it seems to load first without the position and then moves to the position. I presume this is why we have to click back twice. Is there a way to load the page first at the position?

Is there something obviously wrong the way I've gone about this? I am pretty new to all this stuff... Answers on a postcard...

Upvotes: 0

Views: 806

Answers (1)

Tom O'Brien
Tom O'Brien

Reputation: 1831

The way around this is not to use a location hash, but put the hash directly into the $anchorScroll like this:

$anchorScroll("episode12345");

This does not update the location, so when you hit the back button it doesn't need to go to the top of the page - it just goes straight back to the previous location.

Upvotes: 1

Related Questions