How to stop Angular to reboot when address changes

I use Angular scrollTo and anchorScroll as follows:

 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 an Angular page from reloading?

Update: I found that here

https://groups.google.com/forum/?fromgroups=#!msg/angular/BY2ekZLbnIM/MORF-z2vHnIJ

what

The $location service broadcasts a $locationChangeStart event. You can observe that and call event.preventDefault() to stop the navigation. Nice!

can someone tell how to observe this event and prevent by default

+6
source share
5 answers

The update occurs because there is a call to the locationChangeStart event. You can stop this by doing:

 scope.$on('$locationChangeStart', function(ev) { ev.preventDefault(); }); 

In fact, I wrote my own scrollTo directive, which uses this call inside it.

Plnkr / github

My other post about it here

+9
source

You can add the $ event parameter to the ng-click handler:

 <a ng-click="scrollTo('foo', $event)">Foo</a> 

and in the scrollTo function you can do the following:

 scope.scrollTo = function(str, event) { event.preventDefault(); event.stopPropagation(); /** SOME OTHER LOGIC */ } 

But this means that you must manually parse the hash of the target element from element "a".

+6
source

I think this may help u

 $scope.redirectTodiv = function(divname,event) { var id = $location.hash(); $location.hash(divname); $anchorScroll(); $location.hash(id); }; 

from: fooobar.com/questions/940396 / ...

+2
source

This event is fired on rootScope, so you can register an observer using the $on method.

 $scope.$on('$locationChangeStart', function(ev) { ev.preventDefault(); }); 
+1
source

To prevent the page from reloading in the angular anchor, add an empty href attribute.

 <a href ng-click="scrollTo('foo')">Foo</a> OR <a href="" ng-click="scrollTo('foo')">Foo</a> 

doc: https://docs.angularjs.org/api/ng/directive/ngHref

0
source

All Articles