Using $route to obtain URL parameters

I am faced with the challenge of passing the last parameter from the following URL to a $http.get request in my Angular application.

http://myurl.dev/users/32

However, I am struggling to figure out how to pass the 32 as the id.

Here is what I have tried so far:

var matchmaker = angular.module('matchmaker', ['ngRoute'], function($interpolateProvider) {
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
})
.controller('LocationCtrl', ['$scope', '$http', '$location', '$routeParams', '$route', function($scope, $http, $location, $routeParams, $route) {

    var id = $route.current.params.id;

    console.log(id);

    $http.get('http://myurl.dev/services/' + id ).success(function(data) 
    {
        $scope.applicants = data;
    });

}]);

Unfortunately, I'm receiving the following error in the console:

Cannot read property 'params' of undefined

If anyone can provide insight into what might be going wrong, I would greatly appreciate it.

Edit:

Note that the URL being used is generated on the server side, not by Angular.

Edit 2.0

For reference, here is the configuration for the routeProvider with actual route parameters:

var matchmaker = angular.module('matchmaker', ['ngRoute'], function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
})
.config(function($routeProvider, $locationProvider) {
  $routeProvider.when('/matchmaker/locations/:id', {
    controller: 'LocationCtrl'
  });
  $locationProvider.html5Mode(true);
});

Answer №1

To check the value of `$routeParams`, insert a `console.log($routeParams);` in your controller.

If the value is an empty object `{}`, it may be due to a route definition without parameters:

var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider, $locationProvider) {
  $routeProvider.when('/example/:id', {
    templateUrl: 'example.html',
    controller: 'ExampleController'
  });

  // Enable HTML5 mode for links on JSFiddle
  $locationProvider.html5Mode(true);
});

If this is the case, you should see the following output in the console:

Object {id: "42"} 

Answer №2

When working with JavaScript, be aware that you may encounter situations where you are attempting to access a value that is not yet available. In such cases, it is important to specify that you want to retrieve these values only once they are ready by using the '$routeChangeSuccess' event.

.controller('PagesCtrl', function ($rootScope, $scope, $routeParams, $route) {
    // To utilize URL attributes prior to website loading
    $rootScope.$on('$routeChangeSuccess', function () {
        // Access your URL parameters here
        $http.get('http://myurl.dev/services/' + $routeParams.id)
        .success(function(data) {
            $scope.applicants = data;
        });
    });
});

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

Add an element to an array in AngularJS only if there are no existing elements with today's date

Recently, I created a relatively straightforward angularjs function that checks an array for matching dates with today's date. If a match is found, it will not add a new item to the array. However, upon reviewing my code, I can see that it might be a ...

SystemJS is loading classes that are extending others

In my Angular2 application, I have two classes where one extends the other. The first class is defined in the file course.ts (loaded as js) export class Course { id:string; } The second class is in schoolCourse.ts (also loaded as js) import {Cours ...

Utilizing a font URL imported through a script

I am currently working on incorporating the pdfmake package into my application. In order to load fonts, a list of URLs is required during initialization. However, the fonts I am using are managed by npm and Vite, so they do not have fixed URLs. Here' ...

Utilizing traditional JavaScript variables within Express.js or Node.js: A comprehensive guide

How can I successfully export variables from regular JavaScript to be used in ExpressJS? I attempted to use 'exports' but it didn't yield the desired results. For instance, in a regular JS file: var search = 'hello'; exports = s ...

Real-time filtering in personalized dropdown menu with search input

I have been attempting to create a custom list filter for input using a computed property. In one file, I am developing a widget, while in another file, I am implementing it. Below is the code snippet from the widget creation file: <template> ...

Ways to ensure ngModel is accessible across components

I've hit a wall and I'm starting to lose my mind. I've tried all the different methods like FormsModules, ReactiveForms, FORMDIRECTIVES, Input, Output, but I just can't seem to figure out how to make ngModel work between components. My ...

AngularJS endless scrolling from both top and bottom

I have a question regarding the functionality of ngInfiniteScroll. Currently, when using this plugin, more items are loaded as you scroll to the bottom, similar to how Facebook's timeline works. However, I am in need of a reverse functionality where i ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Halt the Bootstrap carousel while entering text in a textarea

Is it possible to achieve this? I think so. I have created a carousel with a form inside. The form includes a textarea and a submit button. Currently, the slider does not slide if the mouse pointer is inside it, which is good. However, if the pointer is o ...

The $broadcast method in AngularJS allows us to send messages to

Is it possible to determine the outcome of $broadcast in AngularJS - whether it was successful or not? $rootScope.$broadcast($scope.abc + ':' + type + 'question', { abcSlug: $scope.abcSlug, questionSlug: questionSlug, abcOb ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

Event follows activation of trigger click

I've already gone through this post on Stack Overflow about triggering an action after a click event, but none of the solutions I've tried so far have worked. Let's say I have a menu on my webpage like this: <ul class="nav nav-tabs"&g ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

When HTML/JS code is utilized, the submit button or image should function to open the same page as

In addition to the left and right mouse buttons, you also have a middle mouse button. If you click on an image or hyperlink with this middle mouse button while browsing any website, it will open a new window in the background. Now, I want to achieve a sim ...

What is the best way to divide the Jquery.js file into smaller, separate files?

My web server has a strict file size limit of 64KB and I heavily rely on jQuery for my project. Unfortunately, using any other library like zepto is not an option. The minified size of jQuery alone is 95KB, so I need to split it into two smaller files. C ...

Prevent removal of item from ngRepeat

Seeking a method to capture the removal of an element within an ngRepeat loop. My goal is to incorporate animations during this process. While handling the addition of elements can be done using the 'link' event, I am uncertain how to intervene d ...

Failure to execute Ajax request when searching for a query

My personal GitHub profile viewer React application allows you to search for a profile by username. By default, my own GitHub username is provided on the landing page. However, when trying to search for another user, my ajax call is not functioning properl ...

Tips for maintaining the original value of a state variable on a child page in ReactJS. Keeping the initial value passed as props from the parent page

Whenever the 'isChildOpen' flag in the parent is true, my child page opens. The goal now is to ensure that the state variable filtered2 in the child component remains constant. While both filtered and filtered2 should initially receive the same v ...