How to extract a segment of a URL using AngularJS

URL could appear as

user/display/31586

or

user/display/31586#section1

Is there a way to retrieve the ID using Angular methods? The navigation is not controlled by Angular. The provided URL opens a page where only certain content is handled by Angular.

Answer №1

The $location service in AngularJS is responsible for parsing the URL from the browser address bar and making it available to your application. In order to use regular URL path and search segments, you need to set html5Mode to true with $locationProvider.

By default, $locationProvider uses hashbangs. If you don't enable html5Mode, attempting to fetch the URL path will result in an empty string.

Once you have set up html5mode, you can leverage the $location service to retrieve the URL path and create custom rules for processing it.

For instance, if your full URL looks like:

http://example.com/person/show/321

In your main.js file, you could have:

angular.module("MyAPP",[],function($locationProvider){
    $locationProvider.html5Mode(true);
});

function MainController($location){
    var pId = $location.path().split("/")[3]||"Unknown";    //path will be /person/show/321/, and array looks like: ["","person","show","321",""]
    console.log(pId);
}

And in your index.html file:

<!DOCTYPE html>
<html lang="en" ng-app="MyAPP">
    <head>
        <meta charset="utf-8">
        <title>Angular test</title>
    </head>
    <body ng-controller="MainController">
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

I hope this information proves useful to you.

Answer №2

For those seeking to retrieve the final fragment of a string, here is an example of how it can be achieved:

function MainController($location){
   var pId = $location.path().split(/[\s/]+/).pop();
     console.log(pId);         //321
}

Answer №3

If you've stumbled upon this page looking for assistance with retrieving the URL in Angular, there may come a time when you need to utilize the absUrl:

console.log($location.absUrl());
http://localhost:8000/dashboard

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

Is it better to perform ASP.Net validation on the client side, the server side, or should it

The official document states: "In most cases, you do not need to make any modifications to your page or validation controls in order to utilize client-side validation." So, does this imply that validation controls will automatically create JavaScript cod ...

What is causing the undefined result when duplicate elements are encountered?

const cardChild = document.querySelectorAll('.card i'); const cardsArray = ['a','a','b','b','c','c']; const matchArray = []; function cardsToClass() { for (i = 0; i < cardChi ...

A guide on transferring the text box value to a disabled text box with javascript

Currently, I am working on a text box where users can enter a value. I would like to dynamically update another disabled text box with the entered value using JavaScript. Regards, Vara Prasad.M ...

I am having trouble with $(this) in my jQuery click event handler

When I click my function, I want to change a parent element that contains this function. However, $(this) is not working. What could be the issue? function accountConfirm(message, title, yes_label, no_label, callback) { console.log($(this)); $(&qu ...

Attempting to implement a unique filter on an ng-repeat that was crafted with creativity

In my current project on Ionic, I have been working on creating a screen that resembles a gallery. It consists of rows with three items in each row. The content is retrieved from a backend, so the code needs to dynamically scale as more items are fetched. ...

Struggling to make jquery-masonry function properly

Coding Challenge <div id="container"> <div class="item"> <p>Lorem ipsum dolor sit amet tail frankfurter brisket, meatloaf beef ribs doner pork prosciutto ball tip rump tenderloin tongue. Pastrami fatback beef, sausage beef ribs venison ...

IE9 encounters an error when using jQuery's .remove() function

While testing my website in IE9 using Firebug Lite, I encountered an issue. When attempting to run a basic command to remove a div, I received an error saying "TypeError: Object expected". The command I used was: $("#drag-hoverbox_you").remove(); Interes ...

Reading an SQL File with Electron and Node.js: A Step-by-Step Guide

I have a local SQL file that is not on a server, and I need to retrieve information from it. What would be the best approach for this? My attempt to install sqlite3 using npm has been unsuccessful as it requires me to first install Microsoft Visual Stu ...

Clicking on items within a list to toggle the display of a specific section using AngularJS directives

I'm brand new to AngularJS and I'm attempting to create a row with 3 elements per row in an ng-repeat. When the user clicks on one of the row elements, another row should appear below it based on the ng-show I have set up. I organized each row in ...

Invoking instance methods of Ajax XMLHttpRequest

function fetchJSONData(url, callback){ var request = new XMLHttpRequest(); request.open('GET', url, true); request.onprogress = function(event){ console.log(event.loaded, event.total); }; request.addEventListener(&apos ...

Is there a way to open an image.png file in typescript using the "rb" mode?

Is there a way to open png files in typescript similar to the python method with open(path+im,"rb") as f:? I have a folder with png files and I need to read and convert them to base 64. Can anyone assist me with the equivalent method in typescript? This i ...

An ajax call triggers a 500 error response when initiated within another ajax call

I am encountering an issue with my Ajax requests. There are two requests - one (referred to as Ajax#1) sends data to the backend, and the other (Ajax#2) uses that data to load content onto the front end. To ensure that Ajax#2 runs after Ajax#1, I attempt ...

How can I direct AngularJs to modify its current location and display an alert in the updated location?

To clarify my question, I am working on a controller and partial for creating a new entity, like a contact. When I click the save button, I call my custom "save" method in the controller. In this method, I use 'contactResource.save' to interact w ...

Leveraging AngularJS with HATEOAS for seamless navigation across different states: a guide on utilizing hypermedia URLs

In my application built with AngularJS, I am utilizing ui router to interact with a REST API that incorporates Hypermedia. The main concept is to have the API generate the URLs for its various calls, rather than having the client construct them. For insta ...

JavaScript, the art of escaping strings

I am dealing with the following string: 'You've just created' When I store this string in a JavaScript variable, it is seen as 2 separate strings due to the presence of a ' character. Is there a way to properly escape it? ...

Resizing a group of 2D SVG shapes in three.js

I'm currently working on creating a map of 2D SVG tiles using three.js. I've utilized SVGLoader() as shown below: loader = new SVGLoader(); loader.load( // resource URL filePath, // called when the resource is loaded ...

Is it possible to remove generic T in typescript if the mysql result value is an array but generic T is not an array?

type User = { name: string email: string } This is the code snippet, import type { PoolConnection, RowDataPacket, OkPacket } from "mysql2/promise"; type dbDefaults = RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[]; type dbQuery& ...

What could be causing my CSS transitions to fail when using jQuery to add classes?

I'm currently working on a website and I'm facing an issue with the transition not functioning as expected. The problem persists even when the 7.css stylesheet is removed and interestingly, the transition works fine when using window:hover. My a ...

Issue with Typescript not recognizing default properties on components

Can someone help me troubleshoot the issue I'm encountering in this code snippet: export type PackageLanguage = "de" | "en"; export interface ICookieConsentProps { language?: PackageLanguage ; } function CookieConsent({ langua ...

What is the process for saving an SVG element from an HTML page as a downloadable text file?

I've been practicing creating SVG elements from scratch on an HTML page using Javascript. The texts within the SVG element are styled with typefaces fetched from the server through a "@font-face" declaration in the CSS file. It's been quite succe ...