What is the best way to extract a URL parameter within a controller?

I'm currently working on a controller that needs to access a URL parameter, but I've hit a roadblock in figuring out how to retrieve this parameter. Here's what I have attempted so far:

Controller:

function CustomerCtrl($scope, $http, $routeParams, $route) {

// var customer_id = $routeParams.id; // unable to make this work
// var customer_id = $route.current.params.id; // also unsuccessful
var customer_id = '58'; // however, this approach seems to be effective

$http({
    url: 'customers/' + customer_id + '/info',
    method: "POST"
})
.success(function (data, status, headers, config) { $scope.name = data; })
.error(function (data, status, headers, config) { $scope.status = status; });
}

App:

var customer = {
    name: 'customer',
    url: '/customer',
    abstract: true,
    templateUrl: 'views/customer/customer.html',
    controller: 'CustomerCtrl'
};

var customer_info = {
    name: 'customer.info',
    parent: customer,
    url: '/:id/info'
    views: {
        view1: { templateUrl: "views/customer/view1.html" },
        view2: { templateUrl: "views/customer/view2.html" }
    }
};

$stateProvider
    .state(customer)
    .state(customer_info);

Can anyone point out where I might be going wrong in my implementation?

Answer №1

Discover an easier way to manage your routes with the ui-router plugin (https://github.com/angular-ui/ui-router). Say goodbye to traditional routing and embrace a state-based approach.

function CustomerCtrl($scope, $http, $routeParams, $route) {

Transform your code to:

function CustomerCtrl($scope, $http, $stateParams, $state) {

And don't forget to update:

var customer_id = $stateParams.id; 

Answer №2

Today was spent in a whirlwind of confusion as I attempted to uncover an angular solution for what seemed like a straightforward, common issue. While many of you may have already come across this answer, the simple solution lies in resorting to good old javascript:

var pathArray = window.location.pathname.split( '/' );
var customer_id = pathArray[3];
$scope.customer_id = customer_id

It's such a basic approach, yet I can't help but feel foolish for overlooking it right from the start.

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

Ways to extract dropdown selection into a .php script

I am trying to capture the selected dropdown value in my .php file, which is used for sending emails. When a user selects one of the 6 options from the dropdown menu, I want that selected option to be included as the email subject. Below is the HTML code ...

The onClick event handler is triggered on page load instead of waiting for a click

Recently delving into React, I encountered an issue while attempting to call a function set as a prop. Take a look at my component below: class SamplesInnerLrg extends Component { playSampleAction(sample,sampleId) { console.log(sample); } ...

Capturing and transfering content from a designated div element to a textarea

Looking to enhance user experience by dynamically adding text to a textarea upon clicking an edit link. Once the edit link is clicked, a pop-up box displays a textarea with the current comment for the user. Multiple .comment-block instances will exist con ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

Troubiling Responsive Menu in React

I am currently working on developing a React Responsive Navigation with SCSS, but I am facing an issue. When I click on the hamburger button, nothing happens and the menu does not slide down in the mobile view. I tried inspecting the code in the browser to ...

Using Javascript to trigger form submission using arrow keys

There are four forms displayed on a single page, and I want each form to be submitted based on the arrow key that is pressed. <form name='go_north' action='' method='post'> <input type='hidden' name=' ...

The JSON sorting functionality seems to be functioning improperly

Here is a sample of my JSON data: [ { "cash": 100, "uid": "LHy2qRGaf3nkWQgU4axO", "name": "test2" }, { "cash": 1000000, "uid": "01wFhCSlnd9vSDY4NIkx", "name": "test" }, { "cash": 500, "uid": "PBOhla0jPwI4PIeNmmPg" ...

Error message: The call stack size limit has been exceeded only on Windows when running `npm start` in a server

While working on the serverless stack guide, I encountered a roadblock early on in Windows 10 (without any issues in Mac or Linux). I set up a basic serverless stack project and ran: npm run start And received this error: RangeError: Maximum call stack ...

Experience the magic of Materialize CSS SideNav

I'm currently attempting to implement the mobile side navigation provided by Materialize. I've managed to display the menu icon, but when I click on it, nothing happens. It seems like the function is not being triggered, and there are no errors s ...

Solving the problem of endless looping in JavaScript tree structures

i have been trying to create a tree structure in JavaScript. However, when I use the add_child function to add a child to an item in the elements array, it adds the child to all items in the elements array and their children, creating an infinite loop. I ...

Having trouble changing the query string in the URL with Angular 4?

My search form includes various filters such as text inputs, checkboxes, and radio buttons. Whenever the user interacts with these filters, the query string in the URL needs to be updated. Consider the following scenario: http://example.com/search?myFilt ...

Map Loader for GeoJson Leaflet Integration

Although my English skills are not perfect, I will do my best to explain my issue. I have some knowledge of javascript / html / ajax and I have created a webgis using Leaflet. The problem arises when loading a large geojson file onto the map - it takes qui ...

What are the steps to utilize my JavaScript class within NodeJS?

Within a JavaScript file, I implemented a class called 'engine' that has a constructor and a method: class engine { constructor(a) { this._a = a; } foo = function() { console.log(this._a); } } module.exports.engine ...

There was a TypeError that was not caught in the promise, stating that the function window.showOpenFilePicker is not valid

Encountering TypeError with File System Web API While experimenting with the File System Web API, I keep receiving a TypeError stating Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function. I am unsure of what is causing this issue. ...

Working with PHP to transfer toggle switch information to JSON

I'm currently experimenting with a combination of HTML, JavaScript, and PHP on a single page. My goal is to update a JSON file with either 0 or 1 based on the toggle switch state change. I seem to be close to achieving this functionality, but upon rel ...

Adding default values to a Vuejs data property

My goal is to populate the predefined data property that I have set. reportGroupData: [ { program_name: "", iteration_name: "", report_template_name: "", toggle: true, report_details: [], }, ] This po ...

What is the best way to rearrange (exchange) elements within an Immutable Map?

Is there a way to rearrange items within an unchangeable list that is part of a Map? Here's an example: const Map = Immutable.fromJS({ name:'lolo', ids:[3,4,5] }); I have attempted to use the splice method for swapping, as well as ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

Angular won't function properly when utilizing the <a href> tag

Within one of my template files (located in a folder named "partials"), I have the following code: <a href="index.html">&laquo; Back to search</a> In one of my JavaScript files, I define the routing as follows: var app=angular.module("ap ...

Having Trouble Styling Radio Buttons with CSS

Hello, I'm facing an issue with hiding the radio button and replacing it with an image. I was successful in doing this for one set of radio buttons, but the second set in another row is not working properly. Additionally, when a radio button from the ...