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?
Edit: Switching to html5Mode should solve my problems but we kinda have to support IE8+ anyway so I fear it's not an accepted solution :/
My solution with ng-route was this simple directive:
The html is looking like:
$anchorScroll
works for this, but there's a much better way to use it in more recent versions of Angular.Now,
$anchorScroll
accepts the hash as an optional argument, so you don't have to change$location.hash
at all. (documentation)This is the best solution because it doesn't affect the route at all. I couldn't get any of the other solutions to work because I'm using ngRoute and the route would reload as soon as I set
$location.hash(id)
, before$anchorScroll
could do its magic.Here is how to use it... first, in the directive or controller:
and then in the view:
Also, if you need to account for a fixed navbar (or other UI), you can set the offset for $anchorScroll like this (in the main module's run function):
Get your scrolling feature easily. It also supports Animated/Smooth scrolling as an additional feature. Details for Angular Scroll library:
Github - https://github.com/oblador/angular-scroll
Bower:
bower install --save angular-scroll
npm :
npm install --save angular-scroll
Minfied version - only 9kb
Smooth Scrolling (animated scrolling) - yes
Scroll Spy - yes
Documentation - excellent
Demo - http://oblador.github.io/angular-scroll/
Hope this helps.
See https://code.angularjs.org/1.4.10/docs/api/ngRoute/provider/$routeProvider
Setting this to false did the trick without all of the above for me.
In my case, I noticed that the routing logic was kicking in if I modified the
$location.hash()
. The following trick worked..