Retrieving parameters from the URL in Angular

I'm facing an issue with my app. I am currently using a factory to manage data for two controllers. When I click on a link that redirects me to another view with a specific URL, I want to reuse the last tag in the URL by slicing it like this:

window.location.pathname.split("/").slice(-1)[0]

However, this method doesn't seem to be working and I'm getting an error message saying: $location is undefined :/ Does anyone have any ideas on how to resolve this? It could be a simple mistake I made, but sometimes having multiple sets of eyes on the problem helps :)

portApp.controller("itemController", ["$scope", "workFactory",
    function($scope, workFactory, $stateParams) {

        console.log(window.location.pathname.split("/").slice(-1)[0]);
        $location.path(); // The console shows that $location is undefined

        var newpath = $stateParams.itemLink;
        $scope.onViewLoad = function(){
            console.log(newpath);
        };
    }
]);

For more context, here is the jsfiddle link - https://jsfiddle.net/d5bjrjov/

Answer №1

The issue in your controller is that you forgot to inject $location, which is why it's showing as undefined.

portApp.controller("itemController", ["$scope", "workFactory",
    function($scope, workFactory, $stateParams) {

To fix this, update the controller like so:

portApp.controller("itemController", ["$scope", "workFactory", '$stateParams', '$location',
    function($scope, workFactory, $stateParams, $location) {

Check your State Provider configuration

You currently have:

 .state('items', {
                url: '/items/{itemLink}',
                controller: 'itemController'
            });

The correct URL pattern for dynamic data is using :itemLink instead of {itemLink} like this:

 .state('items', {
                    url: '/items/:itemLink',
                    controller: 'itemController'
                });

In your controller, you can access this dynamic data using $stateParams.itemLink.

$stateParams.itemLink

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 extracting the title of an image from Flickr?

I have a JavaScript code that randomly pulls single images from Flickr every time the page is refreshed. Now, I want to add a feature where the title of the image is displayed when it's hovered over. However, I've been searching for a solution fo ...

Is there a way in AngularJS to trigger an event at a designated time?

I recently developed a webpage using AngularJS. I am looking to trigger certain actions on my webpage within a specified timeframe. For instance, If it is 2016-01-07 11:00:00, I want ng-show to execute some action. I am utilizing the Angular-timer for ...

Enhancing a popup with animated effects

I have been working on a popup that I want to add a subtle animation to. A fade effect seems like the perfect solution. Here is the code for the button: <a href="javascript:void(0)" onclick="document.getElementById('back_overlay').style.disp ...

What is the best way to show the user's name on every page of my website?

I'm facing an issue where I can successfully capture the username on the home page using ejs after a login, but when transitioning to other pages from the home page, the username is no longer visible. It seems like I am missing some logic on how to ha ...

Getting access to a variable on the client side using express-expose

I'm looking to assign a JavaScript variable on my index.html page once it's returned by express.js. I've attempted to utilize the express-expose middleware, but I'm struggling to figure out how to set the variable in the static HTML pag ...

Show identification as an alternative term in the chart

Is there a way to display an id in a table cell as another name from a different object with corresponding ids? I want to achieve something like this if it's possible: <td class="tableRowText"><p>{{l.SenderId}}</p></td> simil ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

What is the most efficient way to transmit JSON data from a browser to a REST endpoint via Node.js, specifically in gzip format?

Currently working with node.js and express, I have a home page that hits my REST endpoint (PUT) after loading to send some JSON data. The data is not gziped when sending to the endpoint, but I want it to be in gzip form once it reaches the endpoint. Is thi ...

I'm encountering a strange issue where Node JS is mistakenly claiming that the method doesn't exist, even though

Ah, it seems I've encountered an error in my test project. The issue lies with Node JS not being able to locate the getStr function within the Another object. Allow me to share the code with you: test.js var Another = require('./another.js&apo ...

Using Jquery to add a list after parsing JSON data stored in localStorage

I've been stuck on this issue for quite some time now. The problem I'm facing involves checking the localStorage to see if there's a cached JSON string available. If there is, I load it and convert it back into a JSON object. If not, I make ...

Retrieving Dropdown Values based on Selection in Another Dropdown

On my website, there are two dropdown lists available: 1) One containing Book Names 2) The other containing Links to the Books. All data is stored in an XML file structured like this: <?xml version="1.0" encoding="UTF-8"?> <BookDetail> <boo ...

Is it recommended to place the styles created by material-ui for child components after the styles generated for the parent component?

Utilizing material-ui, which utilizes JSS for styling a website. I have a component named Layout that applies margin to all its children (using the all children selector & > * in its style). This functionality works, but I would also like the child ...

Another class is overriding the border of the text-box

I'm facing a challenge in customizing the material ui css. Specifically, I want to set the border color of a textbox to red. The issue arises when the bottom border gets overwritten. Upon investigation, I discovered that the culprit is the class MuiIn ...

Error Message: ES5 mandates the use of 'new' with Constructor Map

Below is the code snippet: export class ExtendedMap<T, U> extends Map { constructor() { super(); } toggle(key: T, value: U) { if (this.has(key)) { super.delete(key); ...

Activate an individual date on the Angular UI Bootstrap datepicker

Currently, I am utilizing the datepicker feature from Angular UI Bootstrap and facing a unique challenge. The first condition that needs to be applied is disabling all days greater than today, which can be easily achieved with the following code: $scope. ...

The serialize() method in Ajax is not capturing all the data fields from an HTML form

Attempting to use the jQuery get() method to send form data from my website, I encountered an issue where only a few of the field data were actually transmitted to the server upon form submission. The Form: <form class="form-horizontal" id="addpost" ...

Is it possible to initiate validation on an HTML element without the presence of a form?

Is it possible to trigger validation on an HTML element without using a form? For example, I have set the required attribute on a field, but when I click the Save button, the field doesn't display the red outline indicating validation failure. I susp ...

What is the process for modifying the user agent?

I'm struggling with phantom, the node.js wrapper for phantomjs. This is the approach needed in native phantomjs. page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/5 ...

What is the process for adding submitted data to an already-existing local JSON file?

I have a new Angular assignment that requires me to push form data into an existing JSON file locally. The task is to develop an Angular application where users can create new tasks and view them on a separate page. Initially, I attempted using http.post ...

Utilize JavaScript to iterate through two sets of numbers

I am currently working on a project that requires me to iterate through two continuous number ranges: 1 to 5 and 10 to 15. This is the code I'm using: var X = []; for (i = 1; i < 6; i++) { X.push(i); } for (i = 10; i < 16; i++) { X.push(i ...