Angularjs regular expressions for URL routing

Is there a way to create a route /:url that matches

http://localhost/#/http://www.google.com

In addition, I am looking for a method to retrieve the URL parameter in the controller using:

var url = $stateParams.url; // url = http://www.google.com

If you have any suggestions on how to achieve this scenario, please let me know. Thank you.

Answer №1

Passing encoded slashes in URLs can be tricky because the browser tends to change them into regular slashes. One solution that has worked for me is double encoding the slashes. I used a helpful online encoder tool, but you can also achieve this within your Angular app using encodeURIComponent. This results in the URL looking like

#/http%3A%252F%252Fwww.google.com
.

In order to set up the parameter, you need to add it to the routing configuration in your app.js file. I added a parameter called url and marked it as optional using the ? symbol:

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
      .when('/:url?', {
        templateUrl: 'view.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
});

Next, in your controller, you can utilize $routeParams to retrieve the URL. Remember to use decodeURIComponent to decode the double-encoded slashes:

app.controller('MainCtrl', function($scope, $routeParams) {
  $scope.url = decodeURIComponent($routeParams.url);
})

Feel free to click on the link provided in the demo to see how the Google URL works.

Check out the Demo

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

dynamically change the information in AngularJS

I need to work with two different endpoints: http://localhost:3000/entry (POST) The keys required are: fname, lname, and age. To submit a form, we have to send a POST request to this URL. http://localhost:3000/entries (GET) This endpoint will retrieve ...

Choose a looping function in React JS that iterates over an array of objects

I have an array of objects let arr = [0: {received: "Return Received", approved: "Approved", rejected: "Rejected"} 1: {authorized: "Authorized", received: "Return Received"}} I am looking to populate a < ...

What are the ways in which I can implement that code with a pair of dropdown menus?

Is it possible to use this code with two dropdown menus? Currently, when I reload the page, the first dropdown menu retains its desired state, but the second one does not. Thank you for any help, I apologize for the beginner question as I am new to this am ...

Angular Component - Array missing initial value in @Input property

Having trouble transferring values between components? I'm currently dealing with a situation involving two components: report-form and comment-form. The report form contains an array of comments, displaying a list of comments and a button for each on ...

What is the method for incorporating an async middleware into a router route?

I am currently setting up routes for an express router in my project. I have a validator that deals with promises, requiring me to use await in the code. Here is how it looks: constructor() { this.router = express.Router(); this.router.use(express. ...

Using jQuery to Retrieve Accurate User Identification - Making AJAX Requests

Currently, I am facing a bit of a dilemma. I have implemented 2 jQuery scripts to handle updating a simple database row based on user ID and session. This functionality allows users to send a "Gift" that adds value to their database row column "bonus". Wh ...

Internet Explorer no longer supports SCRIPT tags in AJAX responses

We are currently facing an issue in our project where AJAX returns some code, and we utilize innerHTML to insert this code into a DIV. Subsequently, we scan this DIV for all script tags and execute the contents of these script tags using EVAL() (which add ...

When trying to inject HTML into AngularJS elements, the data binding may not function

I attempted to reference the documentation but it appears that I may be overlooking something. My goal is to inject HTML that is connected to a JSON object. It functions correctly when the HTML is explicitly declared, however, upon injection and callin ...

Placing error notifications beneath my table rows for a more polished appearance

In the process of creating a review page for my app that showcases uploaded files, I've encountered an issue. Whenever a user uploads files with errors, I want to display a warning message below each specific file. Currently, I'm able to show the ...

Using conditional logic to check if a column cell is empty

I need help writing a Javascript function that will loop through rows in a table and only change the background color of cells in "column2" if they are empty. My current code is not working as expected, as it colors all rows instead of just those with empt ...

Adjust the Angular menu-bar directly from the content-script of a Chrome Extension

The project I've been working on involves creating an extension specifically for Google Chrome to enhance my school's online learning platform. This website, which is not managed by the school itself, utilizes Angular for its front-end design. W ...

Encountering a AngularJS expression issue in Goland

Working on my AngularJS project using Goland is proving to be challenging. Goland is giving me an error on the expression {{ count * times }} like this: https://i.sstatic.net/Ky43G.jpg I've tried enabling the AngularJS plugin on Goland following th ...

javascript for transforming date format

My textfield is set to be a date field with a jQuery datepicker(). The dateFormat() is dd-mm-yy, which works perfectly. However, MySQL requires dates to be in yyyy-mm-dd format. I am wondering if I can convert the date format using PHP or JavaScript before ...

Tips for effectively wrapping Material UI v5 component to ensure the Grow component functions correctly

Being a newcomer to React, I want to apologize in advance for any silly mistakes or inaccuracies that may be present. I have successfully implemented the code for my Blog page: export default function Blog() { const [photos, setPhotos] = useState([]); ...

The problem encountered with Angular ngrx: TypeError when attempting to freeze array buffer views containing elements

I'm running into a problem with ngrx. I have an array in my state to which I am trying to add objects. Everything seems to be working fine as I can see the values in my store when I console log them. However, the redux dev tools and console are throwi ...

Is it possible to launch a Nextjs app on Vercel for production purposes? How well does it handle high volumes of traffic?

As a newcomer to Nextjs, I am looking to deploy my app to production. I'm curious about whether Vercel can effectively handle heavy traffic on the site. Should I consider utilizing platforms such as AWS or GCP for deployment instead? Any advice would ...

What is the most effective method to retrieve the current browser URL in Angular 2 with TypeScript?

Is there a way for me to retrieve the current URL from the browser within my Angular 2 application? Usually in JavaScript, we would use the window object for this task. Can anyone guide me on how to achieve this in Angular 2 using TypeScript? Appreciate a ...

Retrieve JSON data upon refreshing the page

In my blogging application, each post has its own unique permalink structure, such as /post/Dh3hdjs* where Dh3hdjs* represents the specific permalink. However, I am facing an issue where after successfully creating a post and being redirected to the specif ...

Unable to correctly declare and display UTF-8 character within JSON syntax

In my JSON object, there is an attribute that contains a unique special character - I've attempted to save the string in encoded UTF-8 as "\xF0\x9F\x94\x94" or tried displaying it using its HEX value - String.fromCharCode(0x1F514 ...

Obtain JavaScript object from WebView in Swift

Currently, I am displaying a webView in my iOS app using Swift. My goal is to retrieve an object from the JavaScript code within the webView. Upon inspecting the console, I discovered that the desired object is named "window.user". However, when attempti ...