How to change the URL in Angular after the hashbang symbol

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.

Answer №1

It's unclear to me what the issue is...

$location.url('/stuff/after/hash?params=hey');

If you're just looking to update the path after #:

$location.path('/stuff/after/hash');

This is my usual approach. But are you trying to get the url without the hash afterwards? How about

window.location.origin + window.location.pathname

To obtain the current url without hashes and parameters?

Answer №2

Have you thought about using the UI Router? It could be a great solution for your needs.

Overall, it's a fantastic library.

Regarding your specific question, the UrlMatcher service has a method called format that seems to do exactly what you're looking for.

new UrlMatcher('/your/route/here').format(optionalNamedParameters);
// will give you a formatted URL

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Contrast the table column to a JSON object and modify a different column in an HTML file

This Dashboard is my first venture into using HTML and Javascript to create an interactive display. The table within this Dashboard showcases server names, descriptions, and time-related columns for uptime, warning, and critical statuses. To generate an A ...

Can Phaser handle large-scale multiplayer games effectively?

Hello there, I am a newcomer to the world of game development and I am currently delving into phaser with a focus on the isometric plugin. I am curious to find out if it is feasible to design games in phaser similar to agar.io, where handling real-time mu ...

Choose an array containing a random set of n elements and place them into a designated element

I am working on a project where I have a collection of books embedded as iframe elements. My goal is to select three random books from this list and display them within a pre-defined div. However, despite my attempts to use the shuffle method, I am encount ...

Having difficulty generating the HTML list of maps using the code provided in AngularJS

Could someone assist me in displaying the value in HTML for the following code written in angular js? Here is the angularjs controller code : $scope.arr=[new Map().set("MYKEY","MYVALUE")]; And here is the corresponding html code : {{arr}} Any tips on ...

Creating a standalone script using npm JS package for exporting

I'm currently utilizing the npm package manager in my latest project. Within my package.json file, I have a dependency specified: "dependencies": { "litepicker": "^2.0.11" }, The dependency is on litepicker, which i ...

Calculating the percentage in a jQuery Slider

For a while now, I've been using var slideWidth = 420; to set the width of sliders and then $('#slideInner').css('width', slideWidth * numberOfSlides); to calculate the total width of all sliders effectively in pixels. An Issue Ar ...

Using the jQuery .on() method in combination with Respond.js

Recently, I've been experimenting with using .addClass from https://github.com/alexanderholman/Respond in order to dynamically add a class to a div when the browser window resizes and Bootstrap breakpoints change. Here's the Fiddle link for refe ...

Guide on extracting JSON data from specific nodes using d3.js

Just starting out with d3.js and following the example of a simple molecule created by d3 at http://bl.ocks.org/mbostock/3037015. I have a couple questions: 1. How can I select multiple nodes within the molecule structure? 2. Once selected, how do I ext ...

Having trouble with implementing the Drag API Function alongside Javascript Arrow Functions?

I've searched extensively for a similar question but couldn't find one, so I hope this is not a duplicate. Recently, I created a factory function to assist me with drag and drop functionality in my current project. However, I noticed varied beha ...

What could be causing the errors in my subscription function?

Working on an e-commerce website, I encountered errors in the "cartservice" specifically in the "checkoutFromCart()" function. The console displayed the following error: src/app/services/cart.service.ts:218:81 218 this.http.post(${this.serverUrl}ord ...

What is the best way to access the data transferred by a $.ajax function in my PHP script?

An error is popping up on the .php page stating: Notice: Undefined index: name $.ajax({ url: 'test.php', type: "GET", data: ({name: "James"}), success: function(data){ console.log(data); } }); The goal is to retrieve th ...

Explore our product gallery with just a simple hover

I am looking to design a product list page with a mouseover gallery similar to the one showcased on [this page][1]. I attempted to use a vertical carousel like the one illustrated in this Fiddle, but unfortunately, it does not function like Zalando and jc ...

Combine values within a loop and transform them into an object using TypeScript

Being new to typescript, I am unsure how to map values inside a loop. I have a function that performs some logic and returns a number. This function will be called in another function to return two values: a number and a string. export class matrix { ...

What should be the proper service parameter type in the constructor and where should it be sourced from?

Currently, I am faced with a situation where I have two Angular 1 services in separate files and need to use the first service within the second one. How can I properly type the first service in the constructor to satisfy TypeScript requirements and ensure ...

Prevent a hyperlink from being accessible until a timer has finished counting down using J

I have a link with the following HTML: <a class="modal-button" id="submitLink" > When clicked, a jQuery function is triggered which sends an ajax request to my server. I have implemented a countdown timer that displays if the ajax call fails, and ...

Angular $cookieStore failing to hold onto updated cookie when page is refreshed

My current struggle involves $cookieStore's inability to retain a cookie value after it has been updated. Below are two methods from the UserService that handle the cookie: var getCurrentUser = function () { return $cookieStore.get('currentU ...

"What is the way to retrieve the value of a radio button in JavaScript

Greetings, everyone! I am currently struggling with extracting the value of a radio button using JavaScript. Below is the HTML code: <input type="radio" name="gender" id="gender" value="male"> Male</label> <input type="radio" name="gender" ...

Combining several $http.get() functions in ng-init with AngularJS

Currently, I am facing a situation where 2 $http.get() requests are made on page load. These requests are independent of each other. While everything works fine most of the time, there are instances where the second $http.get() request is executed before ...

How can I ensure that the appropriate 'this' is accessed within a callback function for an AJAX request?

When working with a callback function, I am having trouble accessing this. Instead, it seems to be pointing to the AJAX object rather than the object that initially invoked the onClickEmail function. I attempted to store a reference in a variable called th ...

Start the service without the need to include it as an argument

Looking at some older AngularJS code I've inherited, it appears like this: angular .module('MyModule') .directive('MyDirective', []) .controller('MyController', [ 'MyDependency', func ...