3

I am trying to use $anchorScroll and $location.hash() to scroll to a div. I have a bottom on the top of the page. When I click the bottom, I want the page to scroll down to the bottom of the page where I have a <div id="target">.

For some reason, the first time I click the button, my page doesn't scroll. If a click a second time, the page does scroll. And afterwards the scrolling works fine. This weird behavior can be reproduced if I refresh my page.

I have this code in my controller:

$scope.scrolldown = function() {
  $location.hash('target');
  $anchorScroll();
}

I know that the $location.hash('target') line is supposed to append a hash value to the end of my URL.

Here's the URL when my page first got loaded:

http://run.plnkr.co/iqvdGjdeCP4idP4D/

After I clicked my button for the 1st time, it becomes:

http://run.plnkr.co/iqvdGjdeCP4idP4D/#/target

which was not right (and the page was not scrolling properly).

After I clicked my button for the 2nd time, it becomes:

http://run.plnkr.co/iqvdGjdeCP4idP4D/#/target#target

From this point on the page started to scroll properly, but the URL still looks very strange to me -- why would I want two hash values?

I want to know why the button only works after second click and how to correct it.

Update

I added routing to my code and the scroll is working fine now. Here's my plunker demo with routing.

Community
  • 1
  • 1
CherryQu
  • 3,343
  • 9
  • 40
  • 65

1 Answers1

1

Take a look at this question, which contains a possible solution for you: Supress reloading of ui-router based view on query parameter change

It works the second time you click the button because the hash doesn't change (and so the route doesn't reload). Notice the page flickering when you click it the first time? That's an indicator that the whole DOM has been re-rendered.

Community
  • 1
  • 1
HankScorpio
  • 3,612
  • 15
  • 27