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.