Enhancing the visual display of a webpage using AngularJS

Hello there! I'm currently working on enhancing an angular 1.6 app and have encountered a dilemma that needs solving. Let me provide some context: The page in question is a lengthy form consisting of thirty questions. The client-side logic includes numerous conditional statements, for example, if the user selects “Yes” on Q1, then display Q2-4, but if they choose "No" on Q1, skip to Q5. This pattern repeats throughout the extensive form.

Now, here's where things get interesting—what happens if a user mistakenly selects “Yes” on Q1, proceeds to answer Q2-4, and then decides that Q1 should actually be “No”?

So here are my two burning questions: 1) How can I effectively reset or clear the models? And 2) how do I update the view accordingly, ensuring that if they revisit Q1 choosing "Yes", Q2-Q4 are returned to their initial state?

Regarding the first issue, I've devised a simple “clearAll” method as shown below:

function clearAll(arr){
        arr.forEach(function(element){
            if(element!==undefined){
                 element = null; 
            }    
        });
    }

Although this function clears the models, it falls short when it comes to updating the view. How can I ensure that Q2-4 are visually cleared/blank?

My current idea involves updating the view via:

$scope.$watch( myModel, function(val){
    //set to null or delete?
}

However, I am struggling to generalize this solution to make it flexible enough to accommodate an array. Any tips or suggestions would be greatly appreciated. Thank you!

Answer №1

To tackle your specific issue, my recommendation would be to utilize ui-router and resolve different states depending on a question. For example, you could have a state called state.questions where different parameters are taken into account. If your base intro page has the URL /questions (perhaps welcoming users to the questions section), then subsequent URLs like /questions/1 would represent the first question, /questions/2 the second question, and so on.

let questions = [];

This list of objects can be stored in a simple service throughout the application. It can later be populated with objects such as:

{ 
q1: {
  answers: [1,2,3]
},
{
q2: {
  answers: [1,3]
}

You have the option to clear this list once it's no longer needed or add new answers to it. Additionally, you can check for a specific answer before loading the state, offering you the flexibility to achieve your desired outcome.

If you're considering a less elegant solution, you might explore using $watch with a watch group and timeout in the following manner:

$scope.$watchGroup(arrayOfModels, (newVal, oldVal)=>{
  if(newVal) {
   // Perform the desired actions with the models here
   // If they don't take effect, consider using $timeout(()=> $scope.$apply());
  }
})

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 it possible to keep an eye on two different events and take action once they both

I have a menu with different submenus for each list item, all utilizing the same background tag. Currently, when one submenu is open and I hover over another list item, the previous submenus hide and the new one opens. What I want is for the content to cha ...

Troubleshooting Problem with Express Server Routing

I'm currently facing an issue with my error handling while trying to implement a new route to retrieve a user by their id. Below is the code snippet for this specific route. const express = require('express'); require('./db/mongoose&a ...

Receive real-time price updates from Next.js using GetServerSideProps data

I'm currently working on fetching live bitcoin prices from CoinGecko. In my index.js file, I have an async GetServerSideProps function that is functioning correctly. The returned props are then passed down to the <Home /> component, and subseque ...

Sending JSON-encoded data using HTML5 Server-Sent Events (SSE) is a

I have a script that triggers an SSE event to fetch json encoded data from online.php. After some research, I discovered methods for sending JSON data via SSE by adding line breaks. My question is how to send JSON through SSE when the JSON array is genera ...

Use a swipe gesture to move through the slideshow on a touchscreen device

I am currently working on a slideshow that allows users to navigate through images by clicking either the next or previous buttons. When a user clicks on one of these buttons, the next or previous image is loaded into the img src, as shown below. In addit ...

Steps for resolving the error message: "An appropriate loader is required to handle this file type, but there are no loaders currently configured to process it."

I am encountering an issue when working with next.js and trying to export a type in a file called index.ts within a third-party package. Module parse failed: Unexpected token (23:7) You may need an appropriate loader to handle this file type, current ...

JavaScript: Launching the current page in a new tab or window

Is it feasible to open a new window or tab from the existing HTML page? Absolutely, I am referring to the current HTML page itself. Not triggered by an external call like this: window.open('page.html', '_blank'); Possible through Jav ...

Submitting a form triggers the process of uploading images to Firebase

I have been working on a small web app similar to a blog using AngularJs and Firebase. Initially, I successfully implemented the addPost controller. However, when I tried to incorporate an input file within the form to upload images to Firebase upon form s ...

Using vue.js to pass route parameters to a component

I'm encountering an issue with passing a route param directly into a component. Despite following various sets of instructions from the documentation (including using the Composition API as shown in the code snippet below), I continue to receive undef ...

Applying ng-class to the active button

I'm trying to enhance the CSS styling for a selected button in my ServiceNow widget. I've done some research online and managed to grasp the basic structure, but I'm still unsure about properly identifying a selected button and applying the ...

Leverage a custom server (such as NestJS) within NextJS to dynamically render targeted pages

I am experimenting with using NestJS as a custom server for NextJS, following the instructions in this article. Here is a simplified version of the code: @Controller('/') export class ViewController { @Get('*') async static(@Req() r ...

What is the most effective way to display multiple variables simultaneously in Mongoose/Node.js?

As a newcomer to programming, my initial major project involves building a website using Mongoose and Node.js. I have a query regarding rendering two variables for ejs simultaneously without encountering an error due to attempting to render a query that h ...

When conducting tests using Selenium and the headless Google Chrome browser in Java, the dynamic JS content fails to load

Currently, I am in the process of testing a website that I have developed as part of a Spring Boot project using Selenium. While I can successfully test basic functionalities such as page loading and title verification, I am encountering difficulties when ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

communication flow in two directions between server and client

Looking for recommendations on a javascript/nodejs solution that enables bi-directional communication between server and client. The application flow involves the client sending a discovery service to the server, which responds with a challenge. The client ...

"Modify hyperlink attributes to enhance security and optimize user experience

$("a[href*='youtube']").attr('rel', 'prettyPhoto'); Having some trouble targeting links on a page containing "youtube" in the URL. I'm trying to set their rel attribute to "prettyPhoto" so they open in a lightbox window. ...

Creating an HTML list based on a hierarchical MySQL table structure

I have retrieved a hierarchical table showing different elements and their parent-child relationships as follows: id| name | parent_id | header 1 | Assets | 0 | Y 2 | Fixed Assets | 1 | Y 3 | Asset One | 2 | N 4 | ...

Obtaining the result from within the .then() block

Through the utilization of Google's API, I am successful in retrieving and displaying nearby places on the console. router.get('/', function (req, res, next) { // Locating nearby establishments googleMapsClient.placesNearby({ ...

Creating interactive navigation bar effects with scroll and click functionality using jQuery

Is there a way to make the navigation highlight when a user clicks on it and also scrolls to the corresponding section? Currently, I am facing an issue where only the third navigation event highlights, most likely because when navigating to the fourth or f ...

Switching on Closed Captions for HTML5 video while deactivating the standard video controls

I am facing two issues. Whenever I include the track tag in my video element, the default controller of the video pops up, which is causing conflicts with my custom controls. Secondly, I am unable to figure out how to turn closed captions on and off. Thi ...