Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

Do any of you know how to nicely handle anchor hash linking in AngularJS?

I have the following markup for a simple FAQ-page

<a href="#faq-1">Question 1</a>

<a href="#faq-2">Question 2</a>

<a href="#faq-3">Question 3</a>

<h3 id="faq-1">Question 1</h3>

<h3 id="faq-2">Question 2</h3>

<h3 id="fa1-3">Question 3</h3>

When clicking on any of the above links AngularJS intercepts and routes me to a completely different page (in my case, a 404-page as there are no routes matching the links.)

My first thought was to create a route matching "/faq/: chapter" and in the corresponding controller check $routeParams.chapter after a matching element and then use jQuery to scroll down to it.

But then AngularJS shits on me again and just scrolls to the top of the page anyway.

So, anyone here done anything similar in the past and knows a good solution to it?

1 Answer

0 votes
by (106k points)

To handle anchor hash linking in AngularJs you can use the following code:-

app.controller('TestCtrl', function($scope, $location, $anchorScroll) { 

$scope.scrollTo = function(id) { 

$location.hash(id); $anchorScroll(); 

  } 

}); 

<a ng-click="scrollTo('foo')">Foo</a> 

<div id="foo">Here you are</div>

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...