Guidance on AngularJS route parameter passing in view URLs

How can I successfully pass the parameter id in the URL using angularJS? I have tried the following in my home.config:

home.config(["$routeProvider",function ($routeProvider) {
$routeProvider
    .when("/profile",{
        templateUrl : "views/home/profile.html",
        controller  : "profile"
    })
    .when('/settings',{
        templateUrl : "views/home/settings.html",
        controller  : "Settings"
    })
    .when('/item',{
        templateUrl : "views/home/item.html",
        controller  : "item"
    });

}]);

In my home.html:

<a href="#!item?id='+Item_id+'" >Item View</a>

And in my itemController:

controllers.controller("item",function ($scope,$http,$rootScope) {
 var url_string = window.location.href; // home.php#!/item?id=0ae8b2fc-3ccb-11e8-952b-708bcd9109ce
 var url = new URL(url_string);
 var item_id = url.searchParams.get("id");
 console.log(item_id);
})

However, I am getting a value of null. Can someone please assist? Thank you in advance.

Answer №1

When utilizing ngRoute, it is important to utilize $route within the controller in order to access the parameters of the route.

To see a demonstration of this concept, refer to the following code snippet:

const app = angular.module("mainapp", ["ngRoute"]);
app.config(["$routeProvider", function($routeProvider) {
  $routeProvider
    .when("/profile", {
      template: "<p>profile</p>",
      controller: function() {}
    })
    .when('/settings', {
      template: "<p>settings</p>",
      controller: function() {}
    })
    .when('/item', {
      template: "<p>item {{itemid}}</p>",
      controller: function($route, $scope) {
        $scope.itemid = $route.current.params.itemid;
      }
    });
}]);

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

Error encountered when entering a value in the Material UI keyboard date picker

When I select a date by clicking on the calendar, it works fine. However, if I initially set the date to empty and then type in the date, it does not recognize the format and displays numbers like 11111111111111111111. This breaks the date format. If I sel ...

Implementing reCAPTCHA in Spring MVC with Ajax

I've been attempting to implement Google reCAPTCHA service with Spring MVC, but I keep encountering this error in the console: http://localhost:8080/spapp/ajaxtest.htm?name=frfr&surname=frfr&phone=edede…nGi3CCrD9GprYZDn8VHc-pN--SK-u_xoRKOrn ...

Guide to retrieving information from an API and incorporating it into a fresh JSON structure

I am currently working on fetching data from an existing API endpoint and using a part of that data to create a new endpoint in Node.js with Express. Specifically, I am trying to retrieve the userId from https://jsonplaceholder.typicode.com/posts/1 and int ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

Achieve this effect by making sure that when a user scrolls on their browser, 50% of the content is entered into view and the remaining 50%

Is there a way to achieve this effect? Specifically, when the user scrolls in the browser, 50% of the content is displayed at the top and the other 50% is shown at the bottom. ...

The script is stuck displaying the existing records, failing to update with any new ones

Kindly refrain from offering jQuery advice. This script is created to display additional database records when you scroll down to the bottom inside a div named results-container. The issue I'm encountering is that the same data keeps appearing. I&ap ...

I am facing some issues with the React ToDoList project

I'm a student trying to create a ToDoList using React. When I try to submit or remove a schedule, nothing happens and the lists are not updated as expected. However, if I type something in the submission box, it works! I can't seem to figure ou ...

When attempting to execute the npm install command within Visual Studio Code, an error message is being displayed

[ Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Explore the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\Users\sahib\Downloads\generative-art-node-main (1)> npm install npm ERR! code ENO ...

custom checkbox is not being marked as checked

I've been attempting to customize my checkboxes, following various tutorials without success. Despite trying multiple methods, I still can't get the checkboxes to check or uncheck. Here is the code I have so far: https://jsfiddle.net/NecroSyri/ ...

Set element back to its default state

When working with JavaScript, how do you go about restoring the default behavior of a DOM element's event handler? For instance, let's say you've set the onkeypress event for an input element: elem.onkeypress = function() { alert("Key pres ...

Exploring the capabilities of an Angular factory

I am facing challenges in improving the unit test coverage of an Angular project, particularly when trying to test an AngularJS factory with multiple dependencies. The factory I am working on has 5 dependencies, and I am struggling to even write a basic t ...

PHP - Extract Information from Table Upon Form Submission without User Input

I'm facing a challenge with my web form that includes a table allowing users to delete rows before submitting. Although there are no input fields in the table, I need to capture the data from these rows when the form is submitted. The issue is that th ...

Tips for avoiding the persistence of an old array on the screen after refreshing and showing the new, updated array

Currently, my task involves displaying array values on a webpage. The array data is sourced from a real-time database in Firebase. After adding new values to the array or inputting another value into the database on the previous page, we are redirected to ...

Converting time from 00:00:01 to a format of 8 minutes and 49 seconds in Angular

Is there a way to transform a time value from 00:00:01 (not a date object) into a format showing 8 minutes and 49 seconds? Even after consulting the Angular 'date pipe' documentation, I couldn't find a solution to this issue. ...

Every time I switch tabs in Material UI, React rebuilds my component

I integrated a Material UI Tabs component into my application, following a similar approach to the one showcased in their Simple Tabs demo. However, I have noticed that the components within each tab — specifically those defined in the render method ...

Setting up Npm Sequelize Package Installation

Could use some help with setting up Sequelize. Here's the current status: https://i.sstatic.net/MQH1I.jpg ...

Transform the entire division into a clickable link, excluding a specific subdivision that should have its own separate link

I need to create a product layout page where products will be displayed with an image, person's name, title, and description. The challenge is that all of these elements should have one common link except for the person's name that needs a separa ...

Tips for sending images as properties in an array of objects in React

I've been experimenting with various methods to display a background image underneath the "box" in styled components. How can I pass an image as a prop into the background image of the box with the image stored in the array of objects? I'm unsure ...

An undefined error for the variable 'y' in a JavaScript AJAX scenario

I'm completely new to JavaScript and struggling with writing a code that dynamically counts the words on a webpage. Currently, this piece of code is enclosed within a 'whenkeydown' function: var text = $(this).val(); var word=text.split(" ...

Tips for updating the firebase access_token with the help of the next-auth credentials provider

Can anyone help me with refreshing the Firebase access token when it expires? I need the token for API authentication, but I can't find any information online regarding next-auth and Firebase. Currently, I am able to retrieve the access token but str ...