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
we will use window keyup and window keydown event to prevent browser page refresh in angular app.
Clicking on the Reload Page button,will execute the constructor() and ngOnInit() of the AppComponent,ChildComponent and TestComponent again. 3. Clicking on the Reload Test Component button, we will navigate to the /test route and execute the constructor() and ngOnInit() of the TestComponent again.
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.
Plnkr / Github
My other post about this here
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With