The AngularJS UI-Router transition occurs without updating the URL when parameters are passed

When using UI-Router to navigate to a detailed view, I am facing an issue where the state changes correctly and parameters are passed correctly, but the URL address in the browser remains unchanged. I want to be able to display the passed params in the URL.

Here is the code snippet from app.js:

'use strict';

var myApp = angular.module("myApp", ['ui.router']);

myApp.config(['$stateProvider', '$urlRouterProvider','$locationProvider',
       function($stateProvider, $urlRouterProvider,$locationProvider) {


$urlRouterProvider.otherwise('/');

$stateProvider

.state('/', {
url: '/',
templateUrl: 'partials/listView.html'
})

.state('list', {
    url: '/',
    templateUrl: 'partials/listView.html'
})
.state('detail', {
    url: '/detail/:key',
    params: {
         key: { value: "" }
    },
    templateUrl: 'partials/detailView.html',
    controller: 'DetailController'
})

// Using the HTML5 History API
 $locationProvider.html5Mode(true); 
 }]);

Below is the controller function for navigating to the detail state:

myApp.controller('MainContr', [ '$scope', '$http', '$location', '$state',
    '$filter','$rootScope', MainContr ]);

function MainContr($scope, $http, $location, $state, $filter,$rootScope) {

$scope.goDetailView= function(key){
    console.log("trying to change url ");

  // The state changes correctly and passes params to DetailController,
 // however, the browser address URL does not update. 
 // How can I update the URL in the browser here?
    $state.go('detail', 
            {key: $scope.selectedPDFKey},
            {
                location:true
             });        
   }
}

// Detail view controller
myApp.controller('DetailController', [ '$scope', '$stateParams'
    DetailController ]);

function PDFDetailController($scope,$state) 
{
  $scope.currentKey=$state.params.key;
}

If I remove params in $state.go('detail'), the URL in the browser address bar gets replaced. How can I ensure that the URL in the browser address bar also gets updated when passing parameters in $state.go()? Thank you.

Answer №1

The problem was resolved by updating the state to utilize a query in the URL like so:

.state('detailedView', {
   url: '/detailed-view?key',
   params: {
     key: { value: "" }
   },
   templateUrl: 'partials/detailedView.html',
   controller: 'DetailedController'
})

Answer №2

After encountering a problem with my URL, I discovered that the issue was simply a missing / at the start of the link. Here is the incorrect version:

.state('detail', {
  url:         'detail/:key',
  templateUrl: 'tpl.html'
});

And here is the corrected/working version:

.state('detail', {
  url:         '/detail/:key',
  templateUrl: 'tpl.html'
});

I did not need to include any <base> tags in the <head> section of my HTML. My application is located in a subfolder named /app.

Answer №3

By default, UI-Router will display the parameter in the address bar if it is defined in the URL (not just in the params: {} option).

To demonstrate this behavior, a plunker with your specific scenario has been created, showing the expected functionality - http://plnkr.co/edit/9uBlhNoNqZsjAJEdIhYa?p=preview

Useful Links:

<a ui-sref="list">
<a ui-sref="detail({key:1})">
<a ui-sref="detail({key:22})">

Example State Definition (similar to yours):

.state('list', {
  url: '/',
  templateUrl: 'tpl.html',
  controller: 'ParentCtrl',
})
.state('detail', {
  url: '/detail/:key',
  params: { 
    key: { value: "" }
  },
  templateUrl: 'tpl.html',
  controller: 'ChildCtrl',
});

View the demonstration here

(You can open it in a new window by clicking the icon on the top right corner and observe the address bar displaying the key parameter)

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

How can I attach a jQuery plugin to a textbox with a changing class name?

I have a function that converts a regular text field into a datepicker: <input type="text" class="datepicker form-control" name="text-150" > var DatePicker = function () { if ($(".datepicker").length === 0) { return; } $(".datepic ...

AngularJS mdDialog not supporting Tinymce functionality

I'm attempting to integrate the TinyMCE editor into an AngularJS mdDialog. Working Plunker: http://embed.plnkr.co/s3NsemdcDAtG7AoQRvLh/ Plunker with issues: http://embed.plnkr.co/fL8kGLl3b4TNdxW1AtKG/ All features are working fine except for the d ...

HTML/PHP/JS - Submit Form and Upload File Simultaneously

I need to create a form with a Photo Upload Input that allows users to upload pictures before submitting the form for faster processing. The form should also support uploading multiple files, display a progress bar, and provide a preview of the uploaded im ...

Transition the background image color smoothly from left to right in a seamless and continuous movement

A switch button located in the top right corner can toggle between light and dark modes. The background features a zoomed-in image. Currently, the transition is as follows: From left to right when switched to dark mode From right to left when switched to ...

When iterating through a loop, the final value in an array is often overlooked

I have been attempting to iterate through an array to determine if any of the values, when compared to all other values in the array using the modulo operation, do not return a 0. Essentially, this process should only return the prime numbers in the array ...

How can I update an Angular Datatable to display new JSON data?

I have a Datatable controller set up as shown below: //Module / Módulo var angularDataTables = angular.module("angularDataTables", ['datatables', 'datatables.buttons' , 'datatables.bootstrap']); //Controller / Controlador ...

Is there a way to target a sibling element of another element by using its identifier in Cypress?

My current task involves clicking a checkbox within a list of table rows. The only way I can think of reaching this level is by targeting the span tag along with its corresponding name. cy.get('tr > td > span').contains('newCypressTes ...

Is there a way to dynamically count the length of an element or class in realtime using JavaScript?

If there are currently 5 divs with the class name "item" and a new unknown number of divs with the same class name "item" are dynamically added in real time, I want my result to display the total number of divs present at that moment (i.e., 5 + n). Note: ...

Implement a system in Angular Service that automatically generates user IDs for an array of user inputs

How can I automatically increment the user ID for each new user input and use that value for deletion or updating of specific entries? If a user adds their details as shown in the output picture link below, I want to display the output in a similar format ...

Guide to ensuring jQuery Ajax requests are fully processed with WatiN

Currently, I am in the process of developing WatiN tests to evaluate an Ajax web application. However, I have encountered a timing issue with Ajax requests. My main objective is to ensure that WatiN waits for the Ajax request to be completed before valida ...

What methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

Activate the saturation toggle when a key is pressed in JavaScript

I am trying to modify a script that currently toggles the value of a variable when a key is pressed and then lifted. Instead of changing the variable value, I would like to adjust the saturation of the screen based on key presses and releases. How can I ac ...

Tips on utilizing recursive Promises within a loop while transferring arguments to another function

Despite searching other threads on SO, I couldn't find a satisfactory answer to my problem. Every solution seems to be missing something essential for my case, especially since none of them address Apple Music specifically. The Apple API relies heavil ...

Achieve seamless integration of PHP function execution with Javascript onClick without the need for page

After delving into my research, it seems like Ajax and/or JQuery may be the way to go for what I'm trying to achieve. However, I wanted to double-check before moving forward in that direction. The task at hand involves using a javascript onclick func ...

How to Utilize useRef in React Hooks Without Direct Access to HTML Elements?

When working with React, I find myself in a situation where the HTML elements are being loaded from a separate repository that I monitor using pageLoaded. The updateHeader function contains more code for selecting HTML elements and manipulating attributes/ ...

Retrieve all node names from a .dae file using three.js

When I import a collada file into my scene, I am trying to figure out how to list all the node names. Can anyone help me with this? Here is what I have tried so far, but it only gives me one name: var dae; loader.options.convertUpAxis = true; loader.load ...

Transmit the data through AJAX to a node express server

I have been trying to use AJAX to send data to a node express server, but I am facing difficulties in catching the data using express. I want to know how to properly catch the data using express. Here is the code in my NODE file, but nothing seems to be ...

Discovering and substituting particular text on a webpage

Seeking guidance on replacing specific text within an HTML page using AngularJS The text in question is located within a third-party component with changing ID's and classes. The only constant is the actual text that needs to be altered. This partic ...

"Troubleshooting: AngularJS Failing to Display Content in Internet Explorer Version

Exploring the world of angularJS and encountering a little hiccup in HTML. The issue arises when trying to render output after <tr ng-repeat= in Internet Explorer 8. What could be causing this? Referencing a screenshot for clarity. <!DOCTYPE html> ...

Error encountered: WebGL Type error in Three.js

Currently working on a small music visualizer project using WebGL and Three.js with the help of the ThreeAudio.js library. Everything seems to be running smoothly, but I've encountered an error that I'm keen on resolving: "Uncaught Type Error: T ...