If you don't like to use ng-click
here's an alternate solution. It uses a filter
to generate the correct url based on the current state. My example uses ui.router.
The benefit is that the user will see where the link goes on hover.
<a href="{{ 'my-element-id' | anchor }}">My element</a>
The filter:
.filter('anchor', ['$state', function($state) {
return function(id) {
return '/#' + $state.current.url + '#' + id;
};
}])
<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="faq-3">Question 3</h3>
None of the solution above works for me, but I just tried this, and it worked,
<a href="#/#faq-1">Question 1</a>
So I realized I need to notify the page to start with the index page and then use the traditional anchor.
I'm using AngularJS 1.3.15 and looks like I don't have to do anything special.
https://code.angularjs.org/1.3.15/docs/api/ng/provider/$anchorScrollProvider
So, the following works for me in my html:
<ul>
<li ng-repeat="page in pages"><a ng-href="#{{'id-'+id}}">{{id}}</a>
</li>
</ul>
<div ng-attr-id="{{'id-'+id}}" </div>
I didn't have to make any changes to my controller or JavaScript at all.
Try to set a hash prefix for angular routes $locationProvider.hashPrefix('!')
Full example:
angular.module('app', [])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider){
$routeProvider.when( ... );
$locationProvider.hashPrefix('!');
}
])
My solution with ng-route was this simple directive:
app.directive('scrollto',
function ($anchorScroll,$location) {
return {
link: function (scope, element, attrs) {
element.click(function (e) {
e.preventDefault();
$location.hash(attrs["scrollto"]);
$anchorScroll();
});
}
};
})
The html is looking like:
<a href="" scrollTo="yourid">link</a>