I am using Angular's scrollTo and anchorScroll like this:
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>
My problem is that when i click the link the page scrolls down, but in 50% of cases the page reloads because the hash changes in the URL.
How can I prevent Angular from reloading the page?
Update: I have found that here
https://groups.google.com/forum/?fromgroups=#!msg/angular/BY2ekZLbnIM/MORF-z2vHnIJ
that
The $location service broadcasts a $locationChangeStart event. You can observe that and call event.preventDefault() to stop the navigation. Nice!
can anyone tell how to observe that event and prevent default
You can add $event parameter onto ng-click handler:
<a ng-click="scrollTo('foo', $event)">Foo</a>
and in scrollTo function you can do the next:
scope.scrollTo = function(str, event) {
event.preventDefault();
event.stopPropagation();
/** SOME OTHER LOGIC */
}
But that means that you should parse a target anchor hash from an "a" element manually.
The refresh is happening because there is a call to the locationChangeStart event. You can stop this by doing:
scope.$on('$locationChangeStart', function(ev) {
ev.preventDefault();
});
I actually ended up writing my own scrollTo directive that uses this call inside of it.
That event is emitted on the rootScope, so you can register an observer using the $on method.
$scope.$on('$locationChangeStart', function(ev) {
ev.preventDefault();
});
To prevent the page from reloading in an angular anchor, add an empty href attribute.
<a href ng-click="scrollTo('foo')">Foo</a> OR <a href="" ng-click="scrollTo('foo')">Foo</a>