ScrollTo function in AngularJS

后端 未结 9 1890
梦如初夏
梦如初夏 2020-11-27 11:43

I\'m trying to get a quick nav to work correctly. It\'s floating on the side. When they click on a link, it takes them to that ID on the page. I\'m following this guide fro

9条回答
  •  感动是毒
    2020-11-27 12:19

    Thanks Andy for the example, this was very helpful. I ended implementing a slightly different strategy since I am developing a single-page scroll and did not want Angular to refresh when using the hashbang URL. I also want to preserve the back/forward action of the browser.

    Instead of using the directive and the hash, I am using a $scope.$watch on the $location.search, and obtaining the target from there. This gives a nice clean anchor tag

    My element

    I chained the watch code to the my module declaration in app.js like so:

    .run(function($location, $rootScope) {
       $rootScope.$watch(function() { return $location.search() }, function(search) { 
         var scrollPos = 0;
         if (search.hasOwnProperty('scroll')) {
           var $target = $('#' + search.scroll);
           scrollPos = $target.offset().top;
         }   
         $("body,html").animate({scrollTop: scrollPos}, "slow");
       });
    })
    

    The caveat with the code above is that if you access by URL directly from a different route, the DOM may not be loaded in time for jQuery's $target.offset() call. The solution is to nest this code within a $viewContentLoaded watcher. The final code looks something like this:

    .run(function($location, $rootScope) {
      $rootScope.$on('$viewContentLoaded', function() {
         $rootScope.$watch(function() { return $location.search() }, function(search) {
           var scrollPos = 0 
           if (search.hasOwnProperty('scroll')) {
             var $target = $('#' + search.scroll);
             var scrollPos = $target.offset().top;
           }
           $("body,html").animate({scrollTop: scrollPos}, "slow");                                                                                                                                                                    
         });  
       });    
     })
    

    Tested with Chrome and FF

提交回复
热议问题