Skip to content

Commit 131b164

Browse files
IgorMinarbullgare
authored andcommitted
fix($anchorScroll): don't scroll to top when initializing and location hash is empty
Closes angular#8848 Closes angular#9393
1 parent b79d080 commit 131b164

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/ng/anchorScroll.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,10 @@ function $AnchorScrollProvider() {
9494
// (no url change, no $location.hash() change), browser native does scroll
9595
if (autoScrollingEnabled) {
9696
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
97-
function autoScrollWatchAction() {
97+
function autoScrollWatchAction(newVal, oldVal) {
98+
// skip the initial scroll if $location.hash is empty
99+
if (newVal === oldVal && newVal === '') return;
100+
98101
$rootScope.$evalAsync(scroll);
99102
});
100103
}

test/ng/anchorScrollSpec.js

+17
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,12 @@ describe('$anchorScroll', function() {
106106

107107
describe('watcher', function() {
108108

109+
function initAnchorScroll() {
110+
return function($rootScope, $anchorScroll) {
111+
$rootScope.$digest();
112+
};
113+
}
114+
109115
function initLocation(config) {
110116
return function($provide, $locationProvider) {
111117
$provide.value('$sniffer', {history: config.historyApi});
@@ -135,6 +141,7 @@ describe('$anchorScroll', function() {
135141
it('should scroll to element when hash change in hashbang mode', function() {
136142
module(initLocation({html5Mode: false, historyApi: true}));
137143
inject(
144+
initAnchorScroll(),
138145
addElements('id=some'),
139146
changeHashTo('some'),
140147
expectScrollingTo('id=some')
@@ -145,16 +152,25 @@ describe('$anchorScroll', function() {
145152
it('should scroll to element when hash change in html5 mode with no history api', function() {
146153
module(initLocation({html5Mode: true, historyApi: false}));
147154
inject(
155+
initAnchorScroll(),
148156
addElements('id=some'),
149157
changeHashTo('some'),
150158
expectScrollingTo('id=some')
151159
);
152160
});
153161

154162

163+
it('should not scroll to the top if $anchorScroll is initializing and location hash is empty',
164+
inject(
165+
initAnchorScroll(),
166+
expectNoScrolling())
167+
);
168+
169+
155170
it('should not scroll when element does not exist', function() {
156171
module(initLocation({html5Mode: false, historyApi: false}));
157172
inject(
173+
initAnchorScroll(),
158174
addElements('id=some'),
159175
changeHashTo('other'),
160176
expectNoScrolling()
@@ -165,6 +181,7 @@ describe('$anchorScroll', function() {
165181
it('should scroll when html5 mode with history api', function() {
166182
module(initLocation({html5Mode: true, historyApi: true}));
167183
inject(
184+
initAnchorScroll(),
168185
addElements('id=some'),
169186
changeHashTo('some'),
170187
expectScrollingTo('id=some')

0 commit comments

Comments
 (0)