diff --git a/src/ng/anchorScroll.js b/src/ng/anchorScroll.js index 3b25bfe48bca..377f21e5b8c0 100644 --- a/src/ng/anchorScroll.js +++ b/src/ng/anchorScroll.js @@ -94,7 +94,10 @@ function $AnchorScrollProvider() { // (no url change, no $location.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, - function autoScrollWatchAction() { + function autoScrollWatchAction(newVal, oldVal) { + // skip the initial scroll if $location.hash is empty + if (newVal === oldVal && newVal === '') return; + $rootScope.$evalAsync(scroll); }); } diff --git a/test/ng/anchorScrollSpec.js b/test/ng/anchorScrollSpec.js index e7933d630195..2da8a7703bca 100644 --- a/test/ng/anchorScrollSpec.js +++ b/test/ng/anchorScrollSpec.js @@ -106,6 +106,12 @@ describe('$anchorScroll', function() { describe('watcher', function() { + function initAnchorScroll() { + return function($rootScope, $anchorScroll) { + $rootScope.$digest(); + }; + } + function initLocation(config) { return function($provide, $locationProvider) { $provide.value('$sniffer', {history: config.historyApi}); @@ -135,6 +141,7 @@ describe('$anchorScroll', function() { it('should scroll to element when hash change in hashbang mode', function() { module(initLocation({html5Mode: false, historyApi: true})); inject( + initAnchorScroll(), addElements('id=some'), changeHashTo('some'), expectScrollingTo('id=some') @@ -145,6 +152,7 @@ describe('$anchorScroll', function() { it('should scroll to element when hash change in html5 mode with no history api', function() { module(initLocation({html5Mode: true, historyApi: false})); inject( + initAnchorScroll(), addElements('id=some'), changeHashTo('some'), expectScrollingTo('id=some') @@ -152,9 +160,17 @@ describe('$anchorScroll', function() { }); + it('should not scroll to the top if $anchorScroll is initializing and location hash is empty', + inject( + initAnchorScroll(), + expectNoScrolling()) + ); + + it('should not scroll when element does not exist', function() { module(initLocation({html5Mode: false, historyApi: false})); inject( + initAnchorScroll(), addElements('id=some'), changeHashTo('other'), expectNoScrolling() @@ -165,6 +181,7 @@ describe('$anchorScroll', function() { it('should scroll when html5 mode with history api', function() { module(initLocation({html5Mode: true, historyApi: true})); inject( + initAnchorScroll(), addElements('id=some'), changeHashTo('some'), expectScrollingTo('id=some')