Our application serves static angular app files from foobar.com/public/angular
. The home page (foobar.com
) is set up to serve
foobar.com/public/angular/index.html
. This leads us to include the following in the <head>
section of our index file:
<base href="http://foobar.com/public/angular">
During development, we utilize foobar.com/debug
, which directs the server to use this URL instead:
<base href="http://foobar.com/public/angular-debug">
The server returns raw versions (not minified or uglified) of the files from this location. Additionally, we are implementing angular-route for our views.
Summary:
- We have a production route:
foobar.com
- We have a development route:
foobar.com/debug
- A base tag is defined as:
<base href="http://foobar.com/public/whatever">
- We are using hash-bang URLs for angular routes
The challenge lies in generating URLs on the client side. As discussed, using
<a href="#/new/route">Click here</a>
does not work due to the base tag being added to the resulting URL, which the server rejects and causes confusion as users start at a different point: foobar.com/public/angular/#/myRoute
). To create the desired URL format, the best approach I could think of was:
/**
* Returns current URL after replacing everything after the hashtag with a new string.
*
* @param {string} s - string to replace route with (e.g 'asdf')
* @return {string} - new URL e.g. http://google.com/foobar/#!/asdf
*/
makeRouteUrl = function(s) {
var root = $location.absUrl().match(/.*#!/);
if (root && (root.length > 0)) {
root = root[0];
return( root + s );
} else {
// no hashtag in path? Default to home page (not intended use)
return "/";
}
}
However, this solution may appear cumbersome. Is there an Angular function that eliminates the need for the above method? I've explored functions in $location, $route, etc., but nothing appears to address our complex setup accurately. We require obtaining the URL as a string without navigating (as we support opening in a new tab and need to use ng-href
). Given that Angular applications commonly adopt hash-bang URLs for routing, I presumed there should be a simpler way to modify the route after the hashbang while retaining what precedes it.