Skip to content

Commit 7774381

Browse files
author
Sebastian K
committed
fix($location): $location.path() behaviour when $locationChangeStart is triggered by the browser
Fixed inconsistency in $location.path() behaviour on the $locationChangeStart event when using back/forward buttons in the browser or manually changing the url in the address bar. $location.path() now returns the target url in these cases. Closes angular#4989
1 parent 1d50663 commit 7774381

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

src/ng/location.js

+7-6
Original file line numberDiff line numberDiff line change
@@ -612,16 +612,17 @@ function $LocationProvider(){
612612
// update $location when $browser url changes
613613
$browser.onUrlChange(function(newUrl) {
614614
if ($location.absUrl() != newUrl) {
615-
if ($rootScope.$broadcast('$locationChangeStart', newUrl,
616-
$location.absUrl()).defaultPrevented) {
617-
$browser.url($location.absUrl());
618-
return;
619-
}
620615
$rootScope.$evalAsync(function() {
621616
var oldUrl = $location.absUrl();
622617

623618
$location.$$parse(newUrl);
624-
afterLocationChange(oldUrl);
619+
if ($rootScope.$broadcast('$locationChangeStart', newUrl,
620+
oldUrl).defaultPrevented) {
621+
$location.$$parse(oldUrl);
622+
$browser.url(oldUrl);
623+
} else {
624+
afterLocationChange(oldUrl);
625+
}
625626
});
626627
if (!$rootScope.$$phase) $rootScope.$digest();
627628
}

test/ng/locationSpec.js

+25
Original file line numberDiff line numberDiff line change
@@ -1377,6 +1377,31 @@ describe('$location', function() {
13771377
dealoc($rootElement);
13781378
});
13791379
});
1380+
1381+
it('should return the same $location.path() when $locationChangeStart event occurs no matter the cause of url change', function() {
1382+
inject(function($location, $rootScope, $browser, $window) {
1383+
var log = '',
1384+
base = $browser.url();
1385+
1386+
$rootScope.$on('$locationChangeStart', function() {
1387+
log += $location.path();
1388+
});
1389+
1390+
// change through $location service
1391+
$location.path('/b');
1392+
$rootScope.$apply();
1393+
1394+
// reset location
1395+
$location.path('');
1396+
$rootScope.$apply();
1397+
1398+
// change through $browser
1399+
$browser.url(base + '#/b');
1400+
$browser.poll();
1401+
1402+
expect(log).toEqual('/b//b');
1403+
});
1404+
});
13801405
});
13811406

13821407
describe('LocationHtml5Url', function() {

0 commit comments

Comments
 (0)