Navigating to parameterized state in AngularJS using ui-router through URL is a straightforward process

When attempting to access a ui-router parent or child state by entering its corresponding URL, I encounter redirection to my $urlRouterProvider.otherwise() statement rather than directly accessing the state. While I understand that using ui-sref with an a link is a reliable method to enter a state, typing the state's URL into the browser always leads me to the otherwise route.

For instance, my intention is to navigate to the page state by visiting example.com/#/page in the browser. However, instead of accessing the desired state, I am redirected elsewhere.

In my JavaScript code:

angular.module('app', [ 'ui.router', 'subapp']);
angular.module('app').config(function($urlRouterProvider, $locationProvider) {
    }).controller('appCtrl', function(){});

angular.module('subapp', ['ui.router']);
angular.module('subapp').config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when('#/page/nothing', '/');

    $stateProvider
        .state('page', {
            url: '#/page',
            templateUrl: 'page.tpl.html'
         }) 
         .state('page.edit', {
             url: '/:myparameter',
             templateUrl: 'page-edit.tpl.html'
         });
    $urlRouterProvider.otherwise('/hello');
});

Within Index.html:

<body ng-controller="appCtrl">
This is the index.html file<br>
<a href="#/page">Go to page state</a><br>
<a href="#/page/myparameter">Go to page child state with a parameter</a>
<ui-view></ui-view>

PLNKR: http://plnkr.co/edit/HQziTB2CyJrCvbgzzuJm?p=preview

I should note that I have a subapp service injected into the main app, although I believe this should not affect the fact that the page state is meant to be a 'top-level' state within the <ui-view> of index.html.

How can I enable direct navigation to a URL, even one containing a parameter? The documentation suggests it is feasible, but I am unable to implement it successfully.

Answer №1

It seems like you're getting closer to the solution. There's an updated plunker available for reference. To make your links function properly, remember to include the # symbol (unless you're not using html5Mode).

<a href="#/page">
<a href="#/page/myparameter">
<a href="#/page/11">

In your state definition, ensure that you do not include the hash sign:

.state('page', {
    // change this
    // url: '#/page',
    // to this
    url: '/page',
    ...
.state('page.edit', {
    // change this
    // url: '#/:page',
    // to this
    url: '/:page',

By making these adjustments, the following links should work correctly:

<a ui-sref="page">
<a ui-sref="page.edit({page:123})">
<a ui-sref="page.edit({page:444})">

You can test it out here

Answer №2

It appears that your parameter URL is incorrect. Mapping a URL with a fixed name alongside another URL containing a parameter can lead to confusion during rewrite processes, as it may mistakenly be identified as a variable.

$stateProvider
    .state('page', {
        url: '#/page',
        templateUrl: 'page.tpl.html'
    })
    .state('page.edit', {
        url: '/:myparameter',
        templateUrl: 'page-edit.tpl.html'
    });

To avoid issues, consider structuring your URLs like this:

$stateProvider
    .state('page', {
        url: '/page',
        templateUrl: 'page.tpl.html'
    })
    .state('page.edit', {
        url: '/page/:myparameter',
        templateUrl: 'page-edit.tpl.html'
    });

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

Transmit JSON data through a REST API request body

Looking to send a JSON request via REST, with client code in Node.js and server code in Golang. The structure of the body is as follows: const query = "{\"query\":\"query {n result: application(id: \"fb7b5992-4d0a-4782-acb7-13ae6cc66 ...

Why does my progress bar in React not begin on the left side and instead starting in the middle? (See image for reference)

Image Having an issue with the scrolling progress bar that seems to be stuck in the middle and moving in both directions, which doesn't look visually appealing. Can anyone suggest how to resolve this? Interestingly, the same code works fine on online ...

Call a function of a javascript object from inside a callback function

In a user script, I have defined the MyClass and its methods as follows: function MyClass() { this.myCallback = function() { alert("MyClass.myCallback()"); }; this.startRequest = function() { GM_xmlhttpRequest({ &a ...

The function does not modify the content of an element in Internet Explorer versions 10 to 11

I'm currently working on a layout that needs to support IE10-11. Everything seems to be functioning well overall, except for the .text jQuery method. My goal is to have certain elements change their text when a button on the page is clicked, based on ...

Encountering an issue with React npm causing errors that I am unable to resolve

Hey there, I'm a newbie to React. After setting everything up, I encountered an error after running "npm start." Can anyone help me figure out how to fix this? Thanks in advance! Click here for image description ...

Is it possible to modify an element within a list based on the identifier of its containing div?

I have created some additional software for my project, which includes a large div with smaller divs inside. Here is an example of how it is structured: <div class="scroll-area" id="lista"> <div class="box" id="item1"> < ...

The Three JS on the website is error-free, yet it fails to function properly

I've been attempting to replicate the example three.js page on my own website, complete with a canvas for the 3D animation. However, I'm encountering an issue where nothing is displayed, despite no errors appearing. I've tried troubleshootin ...

Replacing text within a paragraph using D3.js

Is it possible to develop a D3 function that can choose a paragraph, delete its content, and replace it with new text? If so, what would be the most effective way to accomplish this? I attempted the following: d3.select("#triggerButton") .on("clic ...

I'm having trouble executing the straightforward code I discovered on GitHub

https://github.com/Valish/sherdog-api Upon downloading the sherdog-api, I embarked on installing node.js as a prerequisite for using this new tool, despite having no prior experience with such software. Following that, I opened up the command prompt and n ...

Verify the pop-up browser window that appears when the page begins to reload using Cucumber

After completing one scenario, the page automatically refreshes. A JavaScript modal is displayed on the website asking the user "Are you sure you want to leave the page?" I need to confirm that modal, but every time I try to create a step for it, I encount ...

Is it necessary for React components to be organized in a hierarchy?

In all my years, I've been told that React components should follow a tree hierarchy so that parent components can manage state and pass it down to their children. But is this truly necessary? The guiding principle of React states that "React has bee ...

Having trouble loading an image after successfully connecting to an API with react.js

I've been working on a custom fetch component to load images from the "the dog API" onto my page. However, I'm facing some issues with getting the images to display correctly. Can anyone spot what might be missing in my setup? App.js import &apo ...

"Maps and Ripple emulator are effective tools for development, but the android emulator does

I attempted to implement a Google Maps code for Cordoba using two different emulators - Ripple Chrome and the standard Android emulator. Surprisingly, Ripple was successful in displaying a geographic location on the map, whereas the Android emulator only ...

E/AndroidRuntime: CRITICAL ERROR: main --- java code in an android app

I've been working on a map application and I've run into some issues. Can anyone help me figure out what's wrong with my code? ERROR 10-25 01:37:41.296 28673-28673/com.onemap.activities E/AndroidRuntime: FATAL EXCEPTION: main 10-25 01:37:4 ...

Switching Primary Menu Selection When Scrolling Through Various Menu Options

I need help with changing the active class of links on my single page scrolling website. I found some useful code snippets for smooth scrolling and updating the active class on scroll or click events: $(document).ready(function () { $(document).on(" ...

Ways to clear TextField status

My question is about a Textfield. In the case where the state is null but the text field value is showing in the Textfield. <TextField style={{ width: '65%'}} id="standard-search" ...

Combining PHP sessions with Vue and Node.js

Currently, I have a PHP application that handles user authentication, MySQL queries, and relies on the $_SESSION cookie for session management. Despite everything working smoothly, I realized the need to enhance the frontend of my application, prompting t ...

Do only the imported functions in a React App contribute to the overall size and overhead for the user?

For instance, my React application relies on the MUI package. However, I am only utilizing the Slider and AutoComplete components from the package. Do only these 2 components impact the performance of my application for the end user? Or does the entire p ...

Combining strings with objects in Javascript: A step-by-step guide

In the code snippet provided, I am combining variables to create a path to another existing object and its attribute. The issue is that I always receive a string, but I would like to somehow convert it into an object. // SET CUSTOM CONTENT FOR COLUMN IF ...

How can you ensure that it selects a random number to retrieve items from an array?

I am experiencing an issue with some code I wrote. Instead of displaying a random object from the array as intended, it is showing the random number used to try and display an object. <html> <body> <h1>HTML random objects< ...