Scroll to anchor after page load in Angular

倾然丶 夕夏残阳落幕 提交于 2019-11-30 11:06:51

So as pointed out, the $anchorScroll has to occur after the page has been rendered, otherwise the anchor doesn't exist. This can be achieved using $timeout().

$timeout(function() {
  $anchorScroll('myAnchor');
});

You can see this plunkr. Make sure to view it in pop-out mode (the little blue button in the upper right corner of the output screen).

Holy moly, this can be accomplished by simply adding autoscroll="true" to your template:

<div autoscroll="true" data-ng-include='"/templates/partials/layout/text-column.html"'></div>

Documentation

Try:

angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  function ($scope, $location, $anchorScroll) {
      $scope.gotoBottom = function() {
      // set the location.hash to the id of
      // the element you wish to scroll to.
      $location.hash('bottom');

      $anchorScroll();
    };
}]);

'bottom' here is the id of your html element to which you want to scroll to.

Documentation here: https://docs.angularjs.org/api/ng/service/$anchorScroll

Maybe you can use native Javascript's Element.scrollIntoView() after the page has been loaded?

my solution

export function onAnchorClick(fragment){

  fragment.subscribe(f=>{
    const element = document.querySelector( "#" + f )
    if ( element ) {
      element.scrollIntoView({behavior: "smooth", block: "center", inline: "center"})
    }

  })
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!