Creating a loop with resolves to navigate through states in AngularJS with ui-router requires the use of a closure

Within our AngularJS app, I am dynamically creating states using ui-router.

Consider an array of states like the following:

const dynamicStates = [
    {name: 'alpha', template: '123'},
    {name: 'bravo', template: '234'}
];

The process of building these states could resemble the example below:

const states = [];
dynamicStates.forEach(state => 
   states.push(
       state: state.name,
       resolve: {
           templateDetails: ['Service', (Service) =>
               Service.getTemplate(state.template)
                   .then(response => response)     
           ]
       }
   )
})
states.forEach(states => $stateProvider.state(state));

In this scenario, the value of state.template within the resolve function consistently remains as '123'. It seems like there may be a closure issue at play here, but understanding how exactly the resolve functions work and what they return has proven to be a challenge. Consequently, closing the scope around state.template has been elusive.

Any insights or suggestions would be greatly appreciated. Thank you!

Answer №1

Great news, I've discovered the answer

Within each resolution, I have implemented a new function that utilizes closureAroundTemplateId to obtain and return the template ID value. This value is then passed on to the subsequent resolve function responsible for fetching the template details.

This approach is demonstrated in the sample code snippet provided below:

function closureAroundTemplateId (type) {
    return function(){
        return type['template'];
    }
}

const states = [];
dynamicStates.forEach(state => 
   states.push(
       state: state.name,
       resolve: {
           templateId: closureAroundFormTemplateId(state),
           templateDetails: ['Service', 'templateId', (Service, templateId) =>
               Service.getTemplate(templateId)
                  .then(response => response)     
               ]
   )
})
states.forEach(states => $stateProvider.state(state));

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 there a way to deliberately trigger an error using Selenium WebDriverIO?

Is there a way to trigger an error using ChromeDriver with Selenium WebDriverIO? I'm not sure if there's a method like browser.fire('error'). ...

Errors encountered during the Angular project build

I need help figuring out what's happening. I keep getting the same error while trying to build my project. I've already attempted deleting typings, angular directory, and performing typings install but nothing seems to be working. All the necess ...

Tips for acquiring the newest router in an angular environment

Is there a way to retrieve and store the URL of the latest router that the user has visited in local storage? Any suggestions would be greatly appreciated. Thank you! ...

What is the best way to transmit a two-dimensional array using ajax?

Here is the process I use to send data to the server: var points = []; var coords = polyline.geometry.getCoordinates(); for (var i = 0; i < coords.length; i++) { var x = (coords[i][0]).toFixed(4); var y = (coords[i][1]).toFixed(4); points[i ...

Can you tell me the appropriate type for handling file input events?

Using Vue, I have a simple file input with a change listener that triggers the function below <script setup lang="ts"> function handleSelectedFiles(event: Event) { const fileInputElement = event.target as HTMLInputElement; if (!fileInp ...

Error encountered during AJAX POST request: NETWORK_ERR code XMLHttpRequest Exception 101 was raised while using an Android device

Here is the ajax post code that I am using: $.ajax({ type: "POST", url: "http://sampleurl", data: { 'email':$('#email').val(), 'password':$('#password').val(), }, cache: false, ...

How is it possible for my search results page to retrieve the words I input?

Currently, I am in the process of creating the search result page and I plan to utilize dynamic routing for implementation. Here is a snippet of my search bar code: <Link href={`/productSearchResult/${searchWord}`}> <a className={styles.navbar_s ...

Can an element be dynamically bound and unbound upon clicking a button in AngularJS?

After creating a display text and an input field, I bound them together using ng-model in the code below: HTML <div ng-app ng-controller="test"> <div ng-bind="content"></div> <input id="txtElem" type="text" ng-model="content" ...

store the id of each li element dynamically into an array

In my code, a list is generated dynamically and each list item has a special id. I am trying to store each li "id" in one array. This is JavaScript code: var i = 0; $("ul#portfolio li").each(function(eval) { var idd = new Array(); idd[i] = $(this ...

Is it possible for a lambda in TypeScript to have access to the class scope but return undefined

In my TypeScript code, I have a class used as a Pipe in Angular 2 to render markdown. It compiles successfully but encounters a runtime exception on a specific line: var Remarkable = require('remarkable'); @Pipe({ name: 'markdown' ...

Enhance your Sails.js model by incorporating a custom instance method as a new property

As a JavaScript programmer still learning the ropes, I encountered a challenge while working with Sails.js and creating a model. Here is what I have so far: module.exports = { tableName: 'FOO_TABLE', attributes: { FOO: 'st ...

Displaying and updating Google Maps within a tab using AngularJS

After spending hours trying to find a solution (even after reading countless pages), I am still struggling with an issue. I have a Bootstrap tabs system on a page, and on the third tab, there is a Google Maps div. Because the tab is not visible initially, ...

React Error: Unable to iterate over this.state.descriptions

Currently facing an issue while trying to resolve this error https://i.stack.imgur.com/BZ304.png The goal is to generate an automated form using the following function: let descriptionsForm = ( <form> {this.state.descriptions.map((d ...

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...

Navigating state: (TypeError): The mapping function for this.state.[something] is invalid

I am currently working on iterating through my state, which contains data retrieved from an external API. However, I encountered this error message: TypeError: this.state.stocks.map is not a function My goal is to display the results on the frontend dyn ...

Flashing text compatibility across all browsers

I'm looking for a way to create text that blinks on all major web browsers. Initially, I attempted using the <blink> HTML tag, but unfortunately, it only works in Mozilla Firefox. Next, I experimented with CSS: <style> .blink {text-deco ...

Unable to traverse the drop-down menu while utilizing ng-repeat

Recently, I encountered an issue with a drop-down menu that I populate using ng-repeat: <div class="btn-group btn-xs" dropdown keyboard-nav> <input id="simple-btn-keyboard-nav" ng-model="available_fields_query" id="single-button" dropdown-toggl ...

Dynamic updating of scores using Ajax from user input

My goal is to design a form that includes three "Likert Scale" input fields. Each of these three inputs will have a total of 10 points that can be distributed among them. The submit button should become enabled when the score reaches 0, allowing users to s ...

RAZOR - Strip image elements from variable with HTML content

In the code snippet below, I am using a helper to display content: @Html.Raw(Model.PageData.PageContent) My goal is to filter out any image tags that may be present. I have explored methods like .substring(), but they require specific indices or string n ...

Error Occurred while Uploading Images using Ajax HTML Editor with JSON Data

I am facing an issue with my AJAX HtmlEditorExtender, specifically when trying to upload an image. The error message I receive is as follows: JavaScript runtime error: Sys.ArgumentException: Cannot de-serialize. The data does not correspond to valid JSON. ...