Skip to content

Commit f1876d1

Browse files
Sebastian Kjamesdaily
Sebastian K
authored andcommitted
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 Closes angular#5089 Closes angular#5118 Closes angular#5580
1 parent 3a36c6e commit f1876d1

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

src/ng/location.js

+7-6
Original file line numberDiff line numberDiff line change
@@ -659,16 +659,17 @@ function $LocationProvider(){
659659
// update $location when $browser url changes
660660
$browser.onUrlChange(function(newUrl) {
661661
if ($location.absUrl() != newUrl) {
662-
if ($rootScope.$broadcast('$locationChangeStart', newUrl,
663-
$location.absUrl()).defaultPrevented) {
664-
$browser.url($location.absUrl());
665-
return;
666-
}
667662
$rootScope.$evalAsync(function() {
668663
var oldUrl = $location.absUrl();
669664

670665
$location.$$parse(newUrl);
671-
afterLocationChange(oldUrl);
666+
if ($rootScope.$broadcast('$locationChangeStart', newUrl,
667+
oldUrl).defaultPrevented) {
668+
$location.$$parse(oldUrl);
669+
$browser.url(oldUrl);
670+
} else {
671+
afterLocationChange(oldUrl);
672+
}
672673
});
673674
if (!$rootScope.$$phase) $rootScope.$digest();
674675
}

test/ng/locationSpec.js

+28
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
describe('$location', function() {
55
var url;
66

7+
beforeEach(module(provideLog));
8+
79
afterEach(function() {
810
// link rewriting used in html5 mode on legacy browsers binds to document.onClick, so we need
911
// to clean this up after each test.
@@ -1401,6 +1403,32 @@ describe('$location', function() {
14011403
dealoc($rootElement);
14021404
});
14031405
});
1406+
1407+
it('should always return the new url value via path() when $locationChangeStart event occurs regardless of cause',
1408+
inject(function($location, $rootScope, $browser, log) {
1409+
var base = $browser.url();
1410+
1411+
$rootScope.$on('$locationChangeStart', function() {
1412+
log($location.path());
1413+
});
1414+
1415+
// change through $location service
1416+
$rootScope.$apply(function() {
1417+
$location.path('/myNewPath');
1418+
});
1419+
1420+
// reset location
1421+
$rootScope.$apply(function() {
1422+
$location.path('');
1423+
});
1424+
1425+
// change through $browser
1426+
$browser.url(base + '#/myNewPath');
1427+
$browser.poll();
1428+
1429+
expect(log).toEqual(['/myNewPath', '/', '/myNewPath']);
1430+
})
1431+
);
14041432
});
14051433

14061434
describe('LocationHtml5Url', function() {

0 commit comments

Comments
 (0)