Ads by ProfitSence
Close

ScrollTo function in AngularJS

Last Updated on Wednesday 5th Oct 2022

AngularJS Scroll to

OverView

  • It also watches the location.hash() and automatically scrolls to match any anchor whenever it changes.
  • This can be disabled by calling anchorScrollProvider.disableAutoScrolling().

Usage

			
					$anchorScroll([hash]);

			
	

Angularjs scrollto. anchorscroll() will help to scroll on specific anchor div id. anchorscroll() is provided by angularjs.

  • We can use it simply. We don't require to write login on code jquery, because it is easy to do using anchorscroll(). anchorScroll will use with location variable hash.

AngularJS Scroll to Element

To make it scroll to a specific element specified by a href, just check attrs.href.

			
					myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function() {
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
      });
    }
  }
});

			
	

Then you could use it like this: <div scroll-on-click></div> to scroll to the element clicked. Or <a scroll-on-click href="#element-id"></div> to scroll to element with the id.

References