3

I have an app with angularjs routing, but on some view i want to scroll to some specific div and i use anchorScroll but sometimes (not all times) it refresh all page even i stop event propagation. Did anyone had this issue?

 $scope.redirectTodiv = function(divname,event) {
    event.stopPropagation();  
    event.preventDefault();

    $location.hash(divname);
    $anchorScroll();

 };
John
  • 1,697
  • 4
  • 27
  • 53
  • can you reproduce issue into a plunkr/jsfiddle/whatever ? – meriadec Sep 19 '14 at 09:34
  • I cant reproduce the error on plunker, but i create one with the same code... http://plnkr.co/edit/QW5YExTbwAtvrDaFVjP7?p=preview – John Sep 19 '14 at 09:57

3 Answers3

21

Try like this

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

 };
sol4me
  • 15,233
  • 5
  • 34
  • 34
  • Thanks! I was experiencing the same issue, and this solved it perfectly. – Daniel Congrove Feb 07 '18 at 20:04
  • This didn't work for me. If the server respond with an error, I want to scroll to the div where the error is displayed. On the first click on "save" button, it doesn't reload the page, but does not scroll, on the second click on save, it does scroll to where it should. – Thomas Sep 14 '20 at 23:46
2

The way to ensure navigation with one click is to combine $location.hash() $anchorScroll and setting routeProvider reloadOnSearch property to false i.e. In your controller code:

$location.hash("editor");
$anchorScroll();

In your route provider:

$routeProvider.when("/masters/voucher", {
    templateUrl: "views/card/voucher.html",
    reloadOnSearch: false
})
David Kabii
  • 642
  • 6
  • 17
  • This worked for me. If the server responds with an error, I want to scroll to the div where the error is displayed. With this fix (reloadOnSearch:false), it worked perfectly. Many Thanks :) – Thomas Sep 14 '20 at 23:47
0

I've two use cases on the same page :

  • When clicking save, if the response is an error, scroll to the errorDiv that displays the error to the user. David Kabii's answer did work for me.
  • However, on the load of the page, in the controller, I want to scroll to a specific area of the page where the user's input is expected. This wouldn't work. I had to use window.setTimeout to workaround this. (there's probably a better way)
      window.setTimeout(function(){
        $location.hash("anchorForm");
        $anchorScroll();
      }, 300);
Thomas
  • 1,231
  • 14
  • 25