$location.url has no effect when given an empty string #10063
Description
Overview of the Issue
$location.url()
is used to update the current URL in the address bar, trigger route changes, etc. It's behaviour is analogous to directly using window.location
to trigger URL changes, but is more Angular-y 😄. However, if you call $location.url('')
, nothing happens!
Expected Behaviour
$location.url('')
updates address bar and $location.url()
to http://www.example.com
Actual Behaviour
$location.url('')
does nothing, neither the address bar nor $location.url()
are changed
Workaround
window.location.pathname = ''
or window.location.href = ''
does change the URL to http://www.example.com
as I would expect, but for a variety of (pretty obvious) reasons, I'd prefer to use $location
for this 👍
Motivation for or Use Case
I am using UI router and have a state defined as my "home" whose URL is an empty string, e.g. http://www.example.com
. Child states append to the path, like /path
, /path/other
, etc.
Everything works fine from a routing perspective: navigating to http://www.example.com
matches the home
state with an empty path, child states update the address bar correctly (using history API on modern browsers, falling back to hashbangs on IE9), etc. However, when navigating back to the home
state, UI router invokes $location.url
with an empty string, and the address bar isn't updated. Therefore, if the user refreshes the page for any reason, they unexpectedly move away from the home
state to wherever they were previously...
Angular Version(s)
I reproduced this in 1.2.25 and 1.3.1. I suspect it's been around for awhile, so maybe I'm just doing something wrong...?
Browsers and Operating System
This problem appears in Chrome & IE9, and affects HTML5 mode and hashbangs.
Reproduce the Error
This Plunkr shows this in practice. Click the $location.url('/path')
button to see $location.url()
update, and then click on $location.url('')
to see that $location.url()
is unaffected.
Plunkr: http://plnkr.co/edit/N6oPdq1RW5kMbvJ9IbfK?p=preview
Related Issues
I searched through the issue database and couldn't find anything related to this, so maybe I'm doing something wrong...
Suggest a Fix
The problem appears to be right here:
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
When PATH_MATCH
runs against "", it matches correctly, so match[1]
is ''
. However, an empty string is falsy, so this.path(...)
is never called, and nothing happens.
Looks like a fairly simple fix, I can likely put a PR together this afternoon if I'm not off base here...