Maintaining parameter values through multiple states using Angular and UI-Router

I am attempting to create a intricate URL structure:

http://example.com/quote/:param1/:param2/:param3/:param4

With the exception of one, each state utilizes the same template.

My inquiry is whether there exists a method to dynamically transfer each parameter to the subsequent state without necessitating multiple templates? Or should I establish individual templates and only modify the ui-sref?

This is my list of states:

.state('quote', {
    url: '/quote',
    ...
})

.state('quote.policy', {
    url: '/',
    templateUrl: 'partials/quote/quote.select.html',
    page: {next: 'location'}
    ...
})

.state('quote.location', {
    url: '/:policy',
    templateUrl: 'partials/quote/quote.select.html',
    page: {next: 'age'}
    ...
})

.state('quote.age', {
    url: '/:policy/:state',
    templateUrl: 'partials/quote/quote.select.html',
    page: {next: 'income'}
    ...
})

.state('quote.income', {
    url: '/:policy/:state/:age',
    templateUrl: 'partials/quote/quote.income-select.html',
    page: {next: 'priority'}
    ...
})

.state('quote.priority', {
    url: '/:policy/:state/:age/:income',
    templateUrl: 'partials/quote/quote.select.html',
    ... 
})

Every param is acquired through a child state of quote. All of them employ the identical template:

snippet from partials/quote/quote.select.html

<label 
    ng-repeat="option in options[page.type]"
    ui-sref="quote.{{page.next}}({ page.type : option.value })" 
    ng-click="formData.selections[page.type] = option.value">

Another hurdle I am facing is that the existing ui-sref does not transmit the value to the URL, thereby failing to append the new value.

Answer №1

After encountering a similar issue, I took matters into my own hands and successfully solved the problem by pinpointing a few mistakes I was making. The solution has also been improved.

One key realization was that the ui-sref property strangely requires an expression:

<label ui-sref="{{ page.next }}({ {{ page.type }} : option.value })">

This requirement seems logical as you cannot substitute variables directly for a property without utilizing the obj[prop] syntax.

Despite suggestions to nest states one after the other from haxxxton, I opted to keep them at only one level down, such as quote.policy, quote.age, etc. Here is an example of the deepest state I implemented:

.state('quote.show', {
    url: '/:policy/:state/:age/:income/:priority/:i',
    templateUrl: '/partials/quote/quote.show.html',
    controller: 'QuoteController'
})

Pay attention to the URL structure.

To make this setup functional, I had to put some thought into it. Passing every previously selected parameter to the next state proved to be challenging since each state does not have awareness of other states' parameters.

The $stateChangeStart event proved to be helpful (in the parent state controller):

$scope.$on('$stateChangeStart', 
function(event, toState, toParams, fromState, fromParams){
    _.each(fromParams, function(val, key){
        toParams[key] = val;
    })
});

By utilizing this event where both the previous state's params and the upcoming state's params are accessible, I managed to append parameters seamlessly. However, the underscore each method was necessary for extracting the key - if there is a better alternative, feel free to share!

This allowed me to generate a functioning URL like:

http://example.com/#!/quote/Sgl/NSW/31-37/tier3/all/

While it is possible to include keywords for each stage in the URL, e.g.,

http://example.com/quote/policy/Sgl/state/VIC...
by incorporating it in the state definition's URL, I chose to avoid this approach.

Embracing the power of Angular!

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

setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically request.onreadystatechange = func. Even though I receive a response from the server when making the ajax ...

The function being called within useEffect is rendering too quickly, causing it to break. However, it functions correctly after

When using React-id-swiper to load images for products, I encountered an issue with setting the useState 'loading' state to false after all images have been successfully loaded. In this case, there are 5 products. To achieve this, I implemented ...

Check that a string field includes specific characters and digits using JavaScript

I'm in the process of developing a React application that includes an input field requiring a specific format: The first four characters (char 1,2,3, and 4) must be "VTF_" followed by numbers for the remaining part of the string. For example, VTF_12 ...

What is the best way to navigate around and close this modal?

Hey everyone, I've been experimenting with the JavaScript on this codepen and I'm trying to make it so that when you click the background, the modal closes. However, I've run into two issues: The .modal is contained within .modal-backgroun ...

After the update to Angular 9, the stopImmediatePropagation function on mat-expansion-panel is no longer functioning as

Issue Description After upgrading to Angular 9, the expected behavior of preventing an expansion panel from opening when editing a field inside was not working. The use of event.stopImmediatePropagation() and event.stopPropagation() did not prevent the exp ...

Tips for addressing the issue - error TS2451: Unable to redefine block-specific variable 'total'

I am currently working on setting up the Jest testing framework and running a basic test (using an example from jestjs.io). Here is the content of the sum.ts file: function sum(a: any, b: any):any { return a + b; } module.exports = sum; And here is the ...

Adding HOST with the sails-mongo adapter: Best practices for seamless integration

I have successfully installed sails-mongo via npm and am currently running a basic sails.js application. However, my host is not being recognized. My MongoDB is operational on the default port 27017. Whenever I generate a model, I encounter an error while ...

Error Detected: the C# script is not compatible with Javascript and is causing

I am facing an issue where I can successfully send information from the database, but I am unable to load the table on the page. When I check the data received with an alert, it appears to be in JSON format, but it still displays the wrong image on the web ...

ES6 AngularJS 1: The Power of $inject and Inheritance

I am facing a situation where I have 3 child controllers that extend a shared parent controller. The structure looks like this: class ParentController { constructor( $scope, $state ){ this.$scope = $scope; this.$state = $state; } } ...

What steps should I take to build a TypeScript project (using tsdx) while excluding the source files from the final output?

My goal is to convert a typescript project into javascript, but I'm encountering an issue where the project's source files are ending up in the dist folder. I suspect it may be related to my configuration settings, as I have reviewed the document ...

The onProgress event of the XMLHttpRequest is triggered exclusively upon completion of the file upload

I have a situation with my AJAX code where the file upload progress is not being accurately tracked. The file uploads correctly to the server (node express), but the onProgress event is only triggered at the end of the upload when all bytes are downloaded, ...

Tips for troubleshooting data saving in a form after clicking the submit button in AngularJS

Recently I started working with Angular JS and I am currently involved in an existing project built on version 1.2.16. Could you please review the following code sample? <form role="form" name="UserCreateForm" novalidate class="biocheck-form"> ...

Validating mandatory fields in C# using Asp.net technology is essential for

Recently, I started exploring ASP.NET. In my project, there are three ASP controls: a textbox, a dropdown, and a submit button. The requirement is that if the dropdown option is selected, then the textbox should be a mandatory field. However, if no dropd ...

Navigating following an AJAX form submission

Currently, I am delving into a problem brought to my attention by a friend. My knowledge of AJAX and jQuery is not very strong. What I have gathered so far is that when this form is submitted, it goes to the current address set_var.cgi with an index of 94, ...

Uploading and previewing files in Angular

Using the ng-file-upload library, I am able to successfully post files to my backend Web Api. The files are saved in the folder: "~/App_Data/Tmp/FileUploads/" The file path is also stored in my database. When I enter edit mode, I want to display a previ ...

Adjust the output number in a JavaScript BMI calculator to the nearest whole number when using the

Hey there, I'm currently working on a beginner project and could use some assistance. My project involves creating a basic BMI calculator using metric units, but I seem to be encountering issues with rounding numbers. Here is a snippet of my code: var ...

redirecting from an AJAX request

Seeking a way to perform a redirect following an ajax `put` request. My intention is to implement client-side validation using pure JS. Client: $(document).ready(function() { login = () => { var username = $("[name='username']"). ...

An error occurred - 0x800a1391 - JavaScript runtime error: The function 'SelectAllCheckBoxes' has not been defined

I'm currently in the process of learning web development and I am trying to incorporate jQuery into my ASP .NET page. Within the header section, I have included the necessary references: <head id="Head1" runat="server"> <link href=" ...

Tips for adjusting column positions in a table while maintaining a fixed header and utilizing both horizontal and vertical scrolling

Is there a way to display a table that scrolls both horizontally and vertically, with the header moving horizontally but not vertically while the body moves in both directions? I have been able to shift the position of the columns, however, I am struggling ...

Storing information in MongoDB with Node.js

Struggling to send data to a MongoDB collection and encountering the error message Cannot POST /courseweb/course/add Experimented with using postman before utilizing axios to pass values. Below is my implementation in the server.js file, leveraging expre ...