From 299f3ca2671e6255a09302bc94817e2f5de7558a Mon Sep 17 00:00:00 2001 From: Thibault Leruitte Date: Wed, 14 Jan 2015 11:36:23 +0100 Subject: [PATCH] fix($location): strip off empty hash segments when comparing Backported from e93710fe0e4fb05ceee59a04f290692a5bec5d20 The url is the same whether or not there is an empty `#` marker at the end. This prevents unwanted calls to update the browser, since the browser is automatically applying an empty hash if necessary to prevent page reloads. Closes #9635 --- src/ng/location.js | 9 +++++++-- test/ng/locationSpec.js | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/ng/location.js b/src/ng/location.js index b523869dd784..89b06e66f972 100644 --- a/src/ng/location.js +++ b/src/ng/location.js @@ -68,6 +68,10 @@ function stripHash(url) { return index == -1 ? url : url.substr(0, index); } +function trimEmptyHash(url) { + return url.replace(/(#.+)|#$/, '$1'); +} + function stripFile(url) { return url.substr(0, stripHash(url).lastIndexOf('/') + 1); @@ -724,10 +728,11 @@ function $LocationProvider(){ // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { - var oldUrl = $browser.url(); + var oldUrl = trimEmptyHash($browser.url()); + var newUrl = trimEmptyHash($location.absUrl()); var currentReplace = $location.$$replace; - if (!changeCounter || oldUrl != $location.absUrl()) { + if (!changeCounter || oldUrl != newUrl) { changeCounter++; $rootScope.$evalAsync(function() { if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). diff --git a/test/ng/locationSpec.js b/test/ng/locationSpec.js index 111f1d14eb96..39437917b4a7 100644 --- a/test/ng/locationSpec.js +++ b/test/ng/locationSpec.js @@ -550,6 +550,20 @@ describe('$location', function() { }; } + describe('location watch', function() { + beforeEach(initService({supportHistory: true})); + beforeEach(inject(initBrowser({url:'http://new.com/a/b#'}))); + + it('should not update browser if only the empty hash fragment is cleared by updating the search', inject(function($rootScope, $browser, $location) { + $rootScope.$digest(); + + $browser.url('http://new.com/a/b#'); + var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').andCallThrough(); + $rootScope.$digest(); + expect($browserUrl).not.toHaveBeenCalled(); + })); + }); + describe('wiring', function() { beforeEach(initService({html5Mode:false,hashPrefix: '!',supportHistory: true}));