最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angularjs $anchorScroll sometimes refresh all page - Stack Overflow

programmeradmin1浏览0评论

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();

 };

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();

 };
Share Improve this question asked Sep 19, 2014 at 9:32 JohnJohn 2,1635 gold badges30 silver badges59 bronze badges 2
  • can you reproduce issue into a plunkr/jsfiddle/whatever ? – meriadec Commented Sep 19, 2014 at 9:34
  • I cant reproduce the error on plunker, but i create one with the same code... plnkr.co/edit/QW5YExTbwAtvrDaFVjP7?p=preview – John Commented Sep 19, 2014 at 9:57
Add a comment  | 

3 Answers 3

Reset to default 21

Try like this

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

 };

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
})

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);
发布评论

评论列表(0)

  1. 暂无评论