$anchorScroll

Scroll to document anchors and coordinate hash-driven scrolling.

$anchorScroll scrolls to the element identified by a hash or, when omitted, to the current value of $location.getHash(), according to the rules specified in the HTML spec.

It also watches the URL hash and automatically scrolls to any matched anchor whenever it is changed by $location.

Exact signatures live in TypeDoc:

Configure

Use module.config({ $anchorScroll: ... }) for application-wide scroll policy.

angular.createModule("app", []).config({
  $anchorScroll: {
    autoScrolling: false,
  },
});

Executable sample: anchor-scroll.html

Manual Scrolling

$location.setHash("details");
$anchorScroll("details");

When automatic scrolling is disabled, call $anchorScroll(...) directly after coordinating routing, animation, or focus.

Vertical Offset

Use the yOffset property to specify a fixed or dynamic vertical scroll offset. This is useful when the application has sticky headers.

Example

<style>
  .demo2 {
    height: 100px;
    overflow: auto;
  }

  .anchor {
    border: 2px dashed DarkOrchid;
    padding: 10px 10px 400px 10px;
  }

  .fixed-header {
    background-color: rgba(0, 0, 0, 0.2);
    height: 50px;
  }

  .fixed-header > a {
    display: inline-block;
    margin: 5px 15px;
  }
</style>

<section id="demo2" class="demo2">
  <div ng-controller="headerCtrl" class="fixed-header">
    <button class="btn" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
      Go to anchor {{x}}
    </button>
  </div>
  <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
    Anchor {{x}} of 5
  </div>
</section>
window.angular
  .createModule('demo2', [])
  .run([
    '$anchorScroll',
    function ($anchorScroll) {
      $anchorScroll.yOffset = 100; // always scroll by 50 extra pixels
    },
  ])
  .controller('headerCtrl', [
    '$anchorScroll',
    '$location',
    '$scope',
    function ($anchorScroll, $location, $scope) {
      $scope.gotoAnchor = function (x) {
        window.$locationTest = $location;
        const newHash = 'anchor' + x;
        if ($location.getHash() !== newHash) {
          // Pass `newHash` to setHash() and
          // $anchorScroll will automatically scroll to it
          $location.setHash('anchor' + x);
        } else {
          // call $anchorScroll() explicitly,
          // since getHash() still returns the same value
          $anchorScroll();
        }
      };
    },
  ]);

window.angular.bootstrap(document.getElementById('demo2'), ['demo2']);
Anchor {{x}} of 5

For detailed method description, see $anchorScroll.