Updating scope within an iteration in AngularJS

I am currently facing an issue with updating subquestions for each question in the code below. Despite my efforts, the subquestions do not update properly and I end up with the same subquestion list for all questions.

How can I display each question along with its corresponding list of subquestions?

  function loadAllQuestionGroup () {
    Questiongroup.query({}).$promise.then(function(group){
        vm.questiongroups = group;
        for(var i=0;i<group.length;i++){
           var grouptitle=group[i].title
            Question.questionsByQuestionGroup({id:group[i].id}).$promise.then(function(question){
                vm.question = question; 
               for(var j=0;j<question.length;j++){    
                  Subquestion.subquestionsByQuestion({id:question[j].id}).$promise.then(function(subquestion){
                      vm.subquestions=subquestion;
                    });                        
              }
         });
        }
      });
    }

 <div ng-repeat="question in vm.question">
   {{question.name}}
   <div ng-repeat="subquestion in vm.subquestions">
     {{subquestion.name}}
   </div>
 </div>

Answer №1

Seems like the issue at hand is not related to angular scope, but rather with vanilla javascript scope that you seem to be struggling with. If you are making asynchronous calls within a loop, you may find yourself consistently receiving the last element. To resolve this, it's recommended to encapsulate promises inside the loop using anonymous functions.

Consider this common example (you can view the setTimeout function as similar to your

Question.questionsByQuestionGroup({id:group[i].id}).$promise
, as they both represent async operations)

//SIMILAR TO YOUR SITUATION
//This will output the value of 'i' as 5 each time due to closure
for (var i = 0; i < 5; i++) {
  setTimeout(function() {
    console.log(i)
  });
}
//Output: 5 5 5 5 5

//HOW IT SHOULD BE HANDLED
//Encapsulate in a wrapper for proper behavior
for (var j = 0; j < 5; j++) {
  (function(index) {
    setTimeout(function() {
      console.log(index)
    });
  })(j);
}
//Output: 0 1 2 3 4

P.S. Once you implement wrappers to fix this issue, your code might become harder to read, so consider refactoring it into separate functions for better maintainability.

Answer №2

Each unique question must be categorized in a question list. A subquestion list should be generated for every individual question. It is necessary to categorize distinct subquestions under their corresponding lists.

function loadAllQuestionGroup () {
    Questiongroup.query({}).$promise.then(function(group){
        vm.questiongroups = group;
        //Set up question list
        vm.questionList = [];
        for (var i=0;i<group.length;i++){
            var grouptitle=group[i].title;
            Question
              .questionsByQuestionGroup({id:group[i].id})
              .$promise
              .then(function(question){
                //Add question to the list
                vm.questionList.push(question); 
                for (var j=0;j<question.length;j++) {
                    //Generate subquestion list
                    question.subquestionList = [];
                    Subquestion
                        .subquestionsByQuestion({id:question[j].id})
                        .$promise
                        .then(function(subquestion){
                             //Add subquestion to the list
                             question.subquestionList.push(subquestion);
                        })
                   ;                        
                };
              })
            ;
        }
    });
}

The iteration of subquestions (ng-repeat) should be done based on the question iterator.

<div ng-repeat="question in vm.questionList">
   {{question.name}}
   <div ng-repeat="subquestion in question.subquestionList">
     {{subquestion.name}}
   </div>
</div>

It's important to note that a subquestionList property has been included in each question within the questionList.

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

Unexpected glitch: three.js texture turns completely black

I am currently working on a simple geometry box that I want to decorate with a texture. However, the box seems to be invisible or completely black. This issue is related to a previous question that can be found here. Following the answer provided by gaitat ...

Utilizing dual submit inputs in a single form with Ajax functionality in Django

This question has been asked three times now, but unfortunately there seems to be no expert available to provide an answer. When using the method in view.py without JavaScript code, everything functions perfectly for both saving and calculating in one for ...

Adding a class on the fly to a particular row within a table

I've implemented a custom directive named "anotherWay" that is supposed to add a class to a table row dynamically after listening to an event. You can find the code for this directive in the customTable.js file located in this Plnkr: http://plnkr.co/ ...

Opening a new window in JavaScript and passing additional parameters

I am facing an issue with my JavaScript link There is a hidden input field named "domain" Below is a div with an onclick script: <div id="button" onclick="window.open('http://www.mylink.nl/?domein=' + document.getElementById('domein&ap ...

Creating a line chart using data from a MySQL database with the help of PHP and

After completing a program, I am now tasked with extracting data from MySQL and presenting it using HTML/PHP. The data retrieval process involves utilizing the mysql.php file: <?php $hostname = "localhost"; $database = "database"; $username ...

What is a more efficient method for verifying the value of an object within an array that is nested within another object in JavaScript?

Is there a more efficient way to check for an object in an array based on a property, without having to go through multiple checks and avoiding potential errors with the ? operator? /** * An API returns a job object like: * { id: 123, name: 'The Job ...

Is it possible to utilize transcluded content within a directive in AngularJS without having to redefine the controller?

My tab control allows me to show or hide content within the control based on the selected tab. The functionality works fine, but I've noticed some odd behavior with the scope when referencing it within transcluded content. It seems like the defined co ...

Having trouble inserting an item into the localStorage array

In my localStorage, I store a list of movies that users have purchased tickets for using an array. However, I am encountering an issue where I cannot add new values to this array in the localStorage. Here is the code snippet: if(window.localStorage){ ...

How can the Material UI select component be customized to automatically scroll to the top when all items are selected?

After implementing the material ui select feature, I observed that when all items are selected, closed, and then reopened, the scroll position is automatically moved to the end. Is there a way to prevent this and keep it at the top? Current display: http ...

The content displayed on body.innerHTML does not match the information found in the page source code

Why is the page source newer than the document.body.innerHTML, and how does this happen? While watching a video on YouTube and inspecting the page source in Chrome's console, I noticed that YouTube assigns a unique signature to all videos. Here are t ...

Create shorter nicknames for lengthy reference names within the ng-repeat loop

Is it possible to assign an alias to a long reference name in ng-repeat? Currently, I have 2 complex objects where one acts as a grouped index for the other. Although the ng-repeat template code is functioning correctly, it's getting hard to read and ...

Occasionally I encounter the message: "Error: Server unexpectedly terminated with status 1."

I created an automated test to check the login page, with testing data stored in a JSON file. Here is the code in index.js: const fs = require("fs"); fs.writeFileSync("testReport.json", "{}", "utf-8"); const { login } = require("./tests/login"); const au ...

Creating a cube with unique textures on each face in three.js r81: What's the best way to achieve this?

After updating to the latest version of three.js, I encountered an issue where THREE.ImageUtils.loadTexture no longer works. As a result, I tried searching for examples of cubes with different faces, but they all utilized the outdated technique "new THREE. ...

Ways to eliminate brackets from a string

Currently, I am working on a challenge involving replacing strings using a function that accepts a string and an object of values. This task involves a two-part algorithm: Replacing values within the string that are enclosed in braces. If the value is wi ...

Make sure to tick off the checkboxes when another checkbox is marked

When a specific condition is met, I want my checkboxes to automatically be checked through Javascript code in MVC. @if (str_item != "" && str_checkroles != "" && str_item == str_checkroles) { <script> src = "https://ajax.googl ...

The JSON object is coming back as null

I need some clarification on why I am getting an "undefined" alert. Any assistance you can offer would be greatly appreciated as this problem is holding up progress on a crucial project. JavaScript $.getJSON("item-data.json", function(results) { ...

Add to an array the recently created span element which was inputted through text in AngularJS

Having some difficulty controlling an array object with a list of span values using a watcher in Angularjs. The current setup works partially - when I input span elements, an array is automatically created for each span. When I remove a span element, the ...

Extracting information from AWS Amplify Graphql API

Graphql Schema : type Media @model { id: ID! title: String type: String } Sample Data : { id: "1234", title: "example image1", type: "image/jpeg", } { id: "5678", title: "ex ...

Angular not functioning properly with alert windows

Here is a snippet of code where I am attempting to create an alert when a button is clicked: <!DOCTYPE html> <html> <head> <title></title> </head> <body ng-app> <button ng-click="alert('test')"> ...

Exploring the Potential of CSS Styling within Vue.js

I am in the process of creating a website and I am looking for a way to manage my styles through Vue. I want to be able to utilize CSS with Vue, as the style of .skill-bar serves as the background of the bar, while .skill-bar-fill represents the green fil ...