Tips for creating a multi-step wizard using AngularJS and incorporating AJAX calls---Crafting a multi

Exploring the creation of a multi-step wizard with ajax calls:

Utilizing ui.router for managing views of the wizard steps, the first page prompts users to input data such as playerid. The second page aims to display information retrieved from the server based on that playerid.

How should this process be structured? There is a concern about controllers being limited to writing to the model, while there is a need to read the user-entered playerid in order to initiate the ajax call...?

Take a look at how it is currently implemented in this Plunk: http://plnkr.co/edit/4ZEdYHUqovn2YfkUpp2y?p=info

Answer №1

If it were up to me, I would have tackled the problem in this manner (check out plunker for reference):

Firstly, setting up the routing like so:

$stateProvider
    .state('view1', {
        url: "/view1",
        templateUrl: "view1.html",
        controller:"WizardCtrlStep1"
    })
    .state('view2', {
        url: "/view2",
        templateUrl: "view2.html",
        controller:"WizardCtrlStep2",
        params:{
          playerId:null
        },
        resolve:{
          player:function($http, $stateParams){
            //You can utilize the player id here
            console.log($stateParams.playerId);
            return $http.get("test.json");
          }
        }
    })

I prefer having a single controller per state as it helps keep things organized and clear.

Additionally, I make use of a resolve to handle the ajax call prior to loading the step2 view.

Below is the controller for the 2nd step:

//I get the resolved value "player" injected
controller('WizardCtrlStep2', function($scope, player) {
  $scope.name = 'World';
  //To access the result of the $http call, use .data
  $scope.player = player.data;
})

And lastly, the HTML markup:

<input type="text" ng-model="main.playerId">
<button ui-sref="view2({playerId:main.playerId})">proceed</button>

In this snippet, I pass a "playerId" parameter to ui-sref which will be utilized in the resolve function.

I hope this explanation was helpful. If you have any queries, feel free to ask.

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

Interacting with Angular 2 Components Inside <router-outlet>

In the header component, there is a search bar. Below that, within the same component, there is a "router-outlet". After pressing enter in the search bar (input field), the search string (event.target.value) should be sent to the component inside the rou ...

Error: Surprising token found in ReactJS application on CodeSandbox

Encountering an unexpected token on line 5 error in my ReactJS project when testing it on CodeSandbox. Interestingly, the app runs smoothly without errors on my local machine. import React, { Component } from 'react'; import Header from ' ...

Issue with AngularJS filter failing to properly filter data

This is the response I received in JSON format from a web service. [{"cid":"41","scname":"Baby Soap","scid":"1"},{"cid":"41","scname":"Baby Powder","scid":"2"},{"cid":"41","scname":"Baby Food","scid":"3"},{"cid":"41","scname":"Diapers","scid":"4"},... // ...

Error: The database query returned duplicate results while using ngRepeat

I have encountered a persistent error that seems to be related to the "fetchCourses()" function in courses.js. Despite various attempts, the error persists and only goes away when I comment out this particular function. My suspicion is on the HTTP request, ...

How can one properly extend the Object class in JavaScript?

I have a scenario where I want to enhance a record (plain Javascript object) of arrays with additional properties/methods, ideally by instantiating a new class: class Dataframe extends Object { _nrow: number; _ncol: number; _identity: number[]; co ...

Tallying the number of words delimited by a comma

Here is how my counter function is structured: function count() { var value = ids.val(); return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(',').length; } After checking the returned value, data is ...

Reactjs encountering issues with function of Cookies section

Currently, I am working on a login module in Reactjs using Nextjs. Upon successful login, I am storing the user email in a cookie. The functionality is working as expected, but I want to restrict access to the login page for users who are already logged in ...

What could be causing the issue of React not showing the messages of "hello" or "goodbye"?

I have a page with a single button that is supposed to display either "hello world" or "goodbye world" when clicked. However, I am facing issues as the messages are not showing up as expected. Below is a screenshot of what the menu items look like when ca ...

Implementing a dynamic module or dependency addition using a webpack plugin: A comprehensive guide

I'm feeling a bit frustrated because what I am trying to accomplish doesn't seem too difficult, but the documentation for webpack is so disorganized that it's eating up a lot of my time. Can someone please explain how I can inject a "dynami ...

Top choice for recording sound and video over the internet

Seeking assistance in finding solutions to enable recording audio and video via web on different platforms such as iPhone and iPad. The recorded media needs to be saved on the server. Any recommendations for a cross-browser compatible approach are apprecia ...

Ways to ensure that a jQuery function does not run until another one has finished

My JQuery functions are as follows: First Function $(function(){ $(".staffDiv div").hide(); $(".staffDiv img").hover(function(){ $(this).next(".staffDetails").slideToggle("slow").siblings(".staffDetails:visible").slideUp("fast"); $(this) ...

Transferring data between two screens within an Ionic app by harnessing the power of angularJS

As a beginner in Ionic and Angular development, I am currently facing an issue with my Ionic application. I have two pages - one with drop-down selects and a submit button, and another page to process the user's choices and display the results. The pr ...

How can I make a polygon or polyhedron using Three.js?

Is it possible to generate polygon or polyhedron shapes in three.js using alternative methods? var customShapePts = []; customShapePts.push( new THREE.Vector2 ( -50, 200 ) ); customShapePts.push( new THREE.Vector2 ( 100, 200 ) ); customShapePts.push( ne ...

Create a JavaScript button that increases a progress bar value by 1 and adjusts its width style by 10 units

Here is the code for managing a progress bar using JavaScript: function getProgress() { return document.getElementById("progressbar").getAttribute("aria-valuenow"); } function setProgress(value) { document.getElementById("progressbar").setAttri ...

ERROR: JSON parsing failed due to an unexpected token "<", indicating an issue with the syntax and structure of the input data

Currently, I am following a tutorial on Scrimba to learn about React and React Router 6. Unfortunately, I have encountered an error with the data provided in the tutorial. The error message reads as follows: 67:1 Uncaught (in promise) SyntaxError: Unexpect ...

Using JavaScript to find the weekday of the same date next year

Struggling to determine the weekday of a particular date next year? Take for example Tuesday, April 19, 2016 as the given date. What we need to calculate is: TUESDAY, April 18, 2017. Consistency with weekdays is crucial in this scenario. The challenge lie ...

The InfiniteScroll feature is experiencing difficulties when used with popups

I'm dealing with links on my page that trigger a full screen popup using the following html code: <div class="movie-popup-container"> <div class="popup"> <-- content of popup --!> </div> </div> My in ...

Error Alert: jQuery Ajax Not Executing

Looking to send form data to PHP using jQuery. Check out the code below. -------------HTML FORM-------------- <div id="createQuestionBlock"> <form id="createQuestionForm" action="" method="POST"> Question Code: <input id="code" ...

utilizing node.js to render angularjs web pages

I am currently working on serving an angularjs page using nodejs. When I open the index.html file directly in the browser, everything works fine: index.html <html lang="en" ng-app="ex1"> <head> <meta charset="UTF-8"> <title& ...

"Troubleshooting a problem with Mongoose's findOne.populate method

There is an array of user IDs stored in the currentUser.follow property. Each user has posts with a referenceId from the PostSchema. I am trying to populate each user's posts and store them in an array called userArray. However, due to a scope issue, ...