Leveraging angular.forEach for JSON Iteration

In my app and controller, I am working on creating a "flow chart style" question and answer system. To keep track of the current question and answer, I am using variables like $scope.ActiveQuestion and an array named $scope.ActiveAnswers.

I am struggling to grasp the concept of AngularJS foreach method as I am more familiar with traditional for loops in JavaScript. Despite searching for explanations comparing foreach to for loops, I have come up empty-handed. However, here is what I am attempting to achieve using the foreach method.

For each answerIDs in the current set of

$scope.questions[$scope.ActiveQuestions].answerIDs
, I aim to access the corresponding array in Answers containing that particular idAnswer and then add it to a newly created empty array called $scope.ActiveAnswers. This process will enable me to use ng-repeat in a template to display the necessary answers for that specific question.

Below, you can examine the JSON data alongside my current Controller code:

app.controller('QuestionsCtrl', function($scope, $http) {

    // Fetch Questions data
    $http.get("includes/getQuestions.php")
    .success(function(response) {
        $scope.Questions = response;
        $scope.ValidAnswers = $scope.Questions[$scope.ActiveQuestion].answerIDs.split(",");
    });
    // Fetch Answers data
    $http.get("includes/getAnswers.php")
        .success(function(response) {
            $scope.Answers = response;
        });

    // Assign First Question
    if ($scope.ActiveQuestion == null) {
        $scope.ActiveQuestion = 1;
    };
    $scope.ActiveAnswers = [];
    angular.forEach($scope.Answers, function(idAnswers) {
        angular.forEach($scope.ValidAnswers, function(value) {
            if(value==idAnswers) {
                this.push(Answers)
            };
        });
    },$scope.ActiveAnswers);

});

Questions:

[
    [], {
        "idQuestion": "1",
        "answerIDs": "1",
        "text": "Don't know what to watch?"
    }, {
        "idQuestion": "2",
        "answerIDs": "2,3,4",
        "text": "Okay! First question: How new to anime are you?"
    }, {
        "idQuestion": "3",
        "answerIDs": "5,6,7,8,9,10",
        "text": "So you're new! Awesome, I've got tons of anime for you. But let's get more specific. What type of anime interests you?"
    }, {
        "idQuestion": "4",
        "answerIDs": "11,12,13",
        "text": "Cool, cool. What setting would you like?"
    }
]

I have also compiled an array of answers:

[
    [], {
        "idAnswer": "1",
        "nextQuestion": "2",
        "text": "Click here to get started",
        "animeID": null,
        "checkType": "0"
    }, {
        "idAnswer": "2",
        "nextQuestion": "3",
        "text": "...I've seen some GIFs",
        "animeID": null,
        "checkType": "0"
    }, {
        "idAnswer": "5",
        "nextQuestion": "4",
        "text": "Fantasy Action Adventure",
        "animeID": null,
        "checkType": "0"
    }, {
        "idAnswer": "11",
        "nextQuestion": null,
        "text": "Steampunk (magic, guns, early 1900s)",
        "animeID": "1",
        "checkType": "1"
    }
]

Although no errors are displayed, the ActiveAnswers array remains unfilled. Any assistance on this matter would be highly appreciated.

UPDATE

Furthermore, it is worth mentioning that I initially store my data in a MySQL database and retrieve it using PHP by encoding it into JSON format.

Answer №1

To effectively manage your requests, you can utilize the promise feature along with the $q.defer() promise manager.

It is important to note that $http inherently returns a promise.

The $q.defer() function provides 2 essential methods:

  • resolve(value) : used to resolve the associated promise by providing the final value

  • reject(reason) : resolves a promise error

In the Controller:

(function(){

function Controller($scope, Service, $q) {


  var defer = $q.defer();

  //creating promises
  var promise1 = Service.get('includes/getQuestions.php"');

  var promise2 = Service.get('includes/getAnswers.php');

  //Creating promise using $q
  var promiseAnswer = defer.promise;

  if ($scope.ActiveQuestion == null) {
      $scope.ActiveQuestion = 1;
  };

  //Retrieving data from promise1 & promise2
  $q.all([promise1, promise2]).then(function(response){
    //Getting question data
    $scope.Questions = response[0].data;
    //Getting answer data
    $scope.Answers = response[1].data;
    $scope.ValidAnswers = $scope.Questions[$scope.ActiveQuestion].answerIDs.split(",");
    $scope.ActiveAnswers = [];

    $scope.Answers.forEach(function(elm){
      $scope.ValidAnswers.forEach(function(value){
        //Accessing elm.idAnswer instead of just elm
        if (value === elm.idAnswer){
          $scope.ActiveAnswers.push(value);
        }
      });
    });

    //Resolving our data
    defer.resolve($scope.ActiveAnswers);

  });

  //Once all data is processed, retrieve the data
  promiseAnswer.then(function(data){
    console.log(data);
  });

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

Additionally, it is recommended to use a Service for processing requests:

Service

(function(){

  function Service($http){

    function get(url){
      //Returns a promise with the specified URL
      return $http.get(url);
    }

    var factory = {
      get: get
    };

    return factory;

  }

  angular
    .module('app')
    .factory('Service', Service);

})();

When dealing with multiple asynchronous requests, utilizing promise and $q.defer() is considered a best practice.

Answer №2

I suggest creating a structure named "Solution" in your code, storing it in an array, and iterating through it like this:

[
 ["Question"],
   ["Solution"]
   {
    "idSolution": "1",
    "nextStep": "2",
    "description": "Click here to begin",
    "animeID": null,
    "validationType": "0"
   },
]

This approach will ensure the loop runs smoothly without any issues.

Answer №3

Thanks to the collaborative effort of everyone here, I successfully resolved the issues with my code without making any changes to the database. I managed to fix the problems with the foreach loops and although there are still some issues remaining, the main challenges in this task have been addressed. Below is the updated version of my code snippet.

app.controller('QuestionsCtrl', function($scope, $http, $window) {

// Setting the initial active question
if ($scope.ActiveQuestion == null) {
    $scope.ActiveQuestion = 1;
};
// Retrieving questions data
$http.get("includes/getQuestions.php").success(function(responseQuestions) {
    $scope.Questions = responseQuestions;
    $scope.ValidAnswers = $scope.Questions[$scope.ActiveQuestion].answerIDs.split(",");

    // Retrieving answers data
    $http.get("includes/getAnswers.php").success(function(responseAnswers) {
        $scope.Answers = responseAnswers;
        $scope.getActiveAnswers();
    });
});

$scope.getActiveAnswers = function() {
    $scope.ValidAnswers = $scope.Questions[$scope.ActiveQuestion].answerIDs.split(",");
    $scope.ActiveAnswers = [];
    angular.forEach($scope.ValidAnswers, function(answerid) {
        angular.forEach($scope.Answers, function(answer) {
            if (answer.idAnswer == answerid) {
                $scope.ActiveAnswers.push(answer);
              };
          });

      }, $scope.ActiveAnswers);
}

$scope.answerclick = function(nextQuestion) {
    $scope.ActiveQuestion = nextQuestion;
    $scope.getActiveAnswers();
};

});

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

An error occurred due to a missing value within the forEach loop

In my JavaScript object, I am encountering an issue with a key. resolve: function () { var result = this.initialValue; console.log('initial value:',result); // 5 this.functions.forEach(function (element, index) { ...

In next.js, when using the DELETE method, make sure to utilize a query parameter rather than

As I work on developing an API, I have encountered an issue with the delete functionality not functioning as expected. When sending a request, I receive a response from this URL: http://localhost:3000/api/admin/categories?id=1 instead of from this URL: ht ...

Transforming JSON data into CSV format using Python

I am seeking assistance with extracting statistical data tables from NHL.com and converting them into CSV format for use in Excel later. While I have successfully extracted the tables, I am encountering difficulties when attempting to convert them to CSV. ...

Explain the functioning of the Node.js event loop and its ability to manage numerous requests simultaneously

Recently, I delved into testing asynchronous code in node.js. From what I understand, when there is an asynchronous operation taking place, Node.js should be able to handle new requests. Below is a snippet of code I wrote using express and axios: app.get(& ...

The JSON response from Ajax is not coming back as anticipated

My attempts to make a basic ajax call are failing; var getPrevious = function(){ console.log('ajaxing'); $.ajax({ type: 'GET', dataType: "json", url: 'http://'+DOMAIN+'/previous', ...

Expanding the properties of an object dynamically and 'directly' by utilizing `this` in JavaScript/TypeScript

Is it possible to directly add properties from an object "directly" to this of a class in JavaScript/TypeScript, bypassing the need to loop through the object properties and create them manually? I have attempted something like this but it doesn't se ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Is it possible to utilize Angular routing with ui.bootstrap.modal service templateUrl in AngularJS?

Exploring the world of Angular for the first time and absolutely enjoying it! I've been trying to develop a modal dialog to showcase a partial view. The ui.bootstap.modal plugin has an interesting option that requires the URL of the partial view to be ...

Require a more efficient strategy for iterating through lines of input

One of the challenges I'm facing with my form is that it contains 5 input lines. I need to keep any blank lines that are sandwiched between two filled lines, while removing all others. For instance, if the first line is blank, the second line contains ...

Guide to dynamically updating the href of an SVG Image in Angular HTML

I am currently iterating through a list of employee objects, each containing an image URL that I need to incorporate into an SVG - Image element. <div *ngFor ="emp of employees"> <defs> <pattern id = "attachedImage" height ...

Why doesn't angular generate ng-reflect-_opened="false" in its production build?

We are currently utilizing the following technologies (which cannot be changed in the near future): Angular 2 RC5 Angular CLI 1.0.0-beta.10 Material Design Side Nav Control Node 6.9.1 npm 3.10.8 Windows 10 When we compile the code (using ng serve with d ...

Add the hue value from Hue into the Chromajs HSL state value

My objective is to dynamically change the background color of a div based on user input. I plan to assign the user's input as the value of the state key hue, and then set another state key called color to hold the HSL representation of the hue using C ...

A guide on manipulating JSON data with the JRS223 preprocessor tool in JMeter

The structure of the JSON body is as follows: { "access_key": "", "erid": "", "ch_sms": { "messages": [ { "urlsh": false, ...

Performing a targeted ajax request to retrieve a set of data

Is it possible to create a collection using a specific ajax call instead of fetching by its URL? Normally, when fetching by a collection, the URL in the collection is used. However, I need to retrieve results from an ajax call rather than the URL. $.ajax( ...

What are the steps for integrating Landbot into a Next.js application?

I've been attempting to integrate Landbot into my Next.js application, but I'm facing some difficulties. I tried to modify the _document.js file and insert the necessary code into the body section, however, it doesn't seem to have any impact ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

HTTP-Proxy load balancing techniques

Currently exploring the http-proxy module. From what I gathered, it balances between two different hosts with the same port. My question is, can it also balance between two different ports while using the same hosts (for example, both hosts having the sa ...

Ways to clear the existing data in a file before adding new content to it?

I have developed a bot that conducts network queries periodically and saves the latest state in a file on disk. Here is the code snippet I am using: let log_file = OpenOptions::new() .read(true) .write(true) .create(true) .open(&log_fil ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

Retrieving both keys and values from a response list in Zabbix API using Python 3

There is an issue I am facing while working with data from zabbix. I have constructed a request as shown below: requests = zapi.host.get({"output": ZabbixApiValues, "selectInventory": ZabbixApiValues, "filter": {"host&quo ...