Dhanush Gopinath
Dhanush Gopinath

Reputation: 5739

Using AngularJS $anchorScroll to scroll to another page's anchor tag

From my AngularJS Home Page I need to scroll to an anchor tag in another page. Both these pages are coming as partial html's into the ng-view component, based on the url. On starting the server, the home page is loaded and from there in need to go to the faq page. I used the normal href with #, but that didn't point to the correct div in the target page. Here is what I tried with $anchorScroll

Here is the controller method

	
$scope.scrollToFaq = function(id) {
   $location.path("/faq")
   $location.hash(id);
   $anchorScroll();
}

Here is how I use it in the home.html

<a ng-click="scrollToFaq('HERE')" href="" class="link">Here</a>

But this is not working properly. If I load the faq page directly and then come back and click the anchor link from the home page, it works. Is it possible to do this with `$anchorScroll

Upvotes: 4

Views: 3530

Answers (3)

Eruvanos
Eruvanos

Reputation: 679

Had the same problem. But fixed it :) Idea is to change to the URL, wait a halfsecond and than jump to the anchor.

HTML:

<a href="" ng-click="goToAnchor('/', 'links')">Links</a>

Controller:

angular.module('exampleApp').controller('NavbarCtrl', function ($scope, $location, $timeout, $anchorScroll) {
      $scope.goToAnchor = function(path, anchor){
          $location.path('/');

          $timeout(function() {
             $anchorScroll(anchor);
          }, 500);
      };
});

Upvotes: 0

svikasg
svikasg

Reputation: 93

Try to use Angular's $timeout service.

$scope.scrollToFaq = function(id) {
 $location.path("/faq");
 $timeout(function(){
   $location.hash(id);
   $anchorScroll();
 }, delay);

here delay would be the time you would like to wait until the anchor scroll happens. I have read about 300ms / 400 ms working for people. When I had this issue, I just had to call the $anchorscroll inside the $timeout. So use what's best for you case.

Note: I am on the lookout for a solution without the use of $timeout. Will update when I find one.

Upvotes: 3

Michelangelo
Michelangelo

Reputation: 5948

Sounds like a history related issue. If the div has already been loaded once it is found immediatly. This solution worked for me in the past. Maybe an idea to wait for the page to load.

$scope.scrollToFaq = function(id) {
    $location.path("/faq");
    $(window).on("load", function(){       
       $location.hash(id);
       $anchorScroll();
    });
    };  

Upvotes: 0

Related Questions