Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Angular to reload when address changes

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

like image 478
user1865341 Avatar asked Mar 18 '13 08:03

user1865341


People also ask

How to stop page refresh in Angular?

we will use window keyup and window keydown event to prevent browser page refresh in angular app.

How refresh component in Angular?

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.


2 Answers

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

like image 182
KhalilRavanna Avatar answered Sep 19 '22 16:09

KhalilRavanna


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.

like image 41
oaleynik Avatar answered Sep 18 '22 16:09

oaleynik