$anchorScroll
Anchor scroll service
Description
$anchorScroll service scrolls to the element hash or (if omitter) to the current value of $location.getHash(), according to the rules speciffied in the HTML spec.
It also watches the URL hash and automatically scrolls to any matched anchor whenever it is changed by $location. This can be disabled by a setting on $anchorScrollProvider.
Additionally, you can use the yOffset property to specify a vertical scroll-offset (either fixed or dynamic).
Example
<style>
#scrollArea {
height: 100px;
overflow: auto;
}
#bottom {
display: block;
margin-top: 2000px;
}
</style>
<section ng-app="demo">
<div id="scrollArea" ng-controller="ScrollController">
<button class="bottom" ng-click="gotoBottom()">Go to bottom</button>
<a id="bottom"></a> You're at the bottom!
</div>
</section>
window.angular.module('demo', []).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.setHash('bottom');
// call $anchorScroll()
$anchorScroll();
};
},
]);
Demo
The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
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
.module('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) {
// set the $location.hash to `newHash` and
// $anchorScroll will automatically scroll to it
$location.setHash('anchor' + x);
} else {
// call $anchorScroll() explicitly,
// since $location.hash hasn't changed
$anchorScroll();
}
};
},
]);
window.angular.bootstrap(document.getElementById('demo2'), ['demo2']);
Demo
Anchor {{x}} of 5
For detailed method description, see $anchorScroll.
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.