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 :/
This may be a new attribute for ngView, but I've been able to get it anchor hash links to work with
angular-route
using thengView autoscroll
attribute and 'double-hashes'.ngView (see autoscroll)
(The following code was used with angular-strap)
You're looking for
$anchorScroll()
.Here's the (crappy) documentation.
And here's the source.
Basically you just inject it and call it in your controller, and it will scroll you to any element with the id found in
$location.hash()
Here is a plunker to demonstrate
EDIT: to use this with routing
Set up your angular routing as usual, then just add the following code.
and your link would look like this:
Here is a Plunker demonstrating scrolling with routing and $anchorScroll
And even simpler:
and your link would look like this:
Sometime in angularjs application hash navigation not work and bootstrap jquery javascript libraries make extensive use of this type of navigation, to make it work add
target="_self"
to anchor tag. e.g.<a data-toggle="tab" href="#id_of_div_to_navigate" target="_self">
I could do this like so:
Based on @Stoyan I came up with the following solution:
This was my solution using a directive which seems more Angular-y because we're dealing with the DOM:
Plnkr over here
github
CODE
HTML
I used the $anchorScroll service. To counteract the page-refresh that goes along with the hash changing I went ahead and cancelled the locationChangeStart event. This worked for me because I had a help page hooked up to an ng-switch and the refreshes would esentially break the app.