Accessing data outside of the scope when looping through items in Angular forEach

I am currently working on retrieving the Game ID generated by the APIService.postData method for the game. The goal is to utilize this Game ID within the Angular foreach loops to maintain foreign key constraints on the RESTful side.

Any advice on extracting the game ID from there?
P.S. I am already familiar with the scope issue.

this.createGame = function() {

    APIService.postData('game', '', $scope.newGameData).then(function (data) {
        $scope.newGameID = data.id;
    });

    // Iterating through each added class and appending the game_id to the object to facilitate smooth DB insertion on the RESTful side.
    angular.forEach($scope.newGameData.classes, function (key, value) {
        $scope.newGameData.classes[value].game_id = $scope.newGameID;
        APIService.postData('game-class', '', $scope.newGameData.classes[value]);
    });

    // Cycling through each added race and adding the game_id to the object to ensure seamless DB insertion on the RESTful side.
    angular.forEach($scope.newGameData.races, function (key, value) {
        $scope.newGameData.races[value].game_id = $scope.newGameID;
        APIService.postData('game-race', '', $scope.newGameData.races[value]);
    });

    $scope.newGameData = {
        name: ""
    };
    $scope.race_counter = 0;
    $scope.class_counter = 0;
    $scope.newGameData.classes = [{id: $scope.class_counter}];
    $scope.newGameData.races = [{id: $scope.race_counter}];

    $scope.successMessage = "New 'Game' has been added!";

    $scope.action = 'showGames'; // Default action.
    this.getGames();
    $window.scrollTo(0, 0);
};

Answer №1

After some trial and error, I discovered that the foreach loops needed to be placed within the 'then' callback function. It turns out that the GameID was showing up as undefined because the POST request had not yet completed. Additionally, the $scope.newGameData was getting muddled, so I stored both arrays in their own local variables, which resolved the issue.

this.createGame = function() {

    var newGameID = '';
    var classData = $scope.newGameData.classes;
    var raceData = $scope.newGameData.races;

    APIService.postData('game', '', $scope.newGameData).then(function (data) {
        newGameID = data.id;

        // Iterating through each added class and assigning the game_id to the object for smooth DB insertion on the RESTful side.
        angular.forEach(classData, function (key, value) {
            classData[value].game_id = newGameID;
            APIService.postData('game-class', '', classData[value]);
        });

        // Looping through each added race and appending the game_id to the object for seamless DB insertion on the RESTful side.
        angular.forEach($scope.newGameData.races, function (key, value) {
            raceData[value].game_id = newGameID;
            APIService.postData('game-race', '', raceData[value]);
        });
    });

    $scope.newGameData = {
        name: ""
    };
    $scope.race_counter = 0;
    $scope.class_counter = 0;
    $scope.newGameData.classes = [{id: $scope.class_counter}];
    $scope.newGameData.races= [{id: $scope.race_counter}];

    $scope.successMessage = "New 'Game' has been successfully added!";

    $scope.action = 'showGames'; // Default action.
    this.getGames();
    $window.scrollTo(0, 0);
};

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

Passing an object in Vue.js during a redirect

i currently have two components named projectListComponent and projectSingleComponent. I want to pass an object from component 1 to component 2 during redirection. Here is my code: projectListComponent.vue <template> <div class="row justify ...

Creating a nested function and utilizing the return statement in JavaScript

I am facing an issue with my custom function that contains an ajax call. I need to retrieve a variable from the ajax function within my custom function, but I'm unable to do so. Why is this happening? Possible solution 1: <script> function ...

Customize the Color of Your Material-UI Drawer

Need help with setting the background color of a Material-UI Drawer. I tried using the following code but it didn't work: const styles = { paper: { background: "blue" } } After defining the styles, I passed them to the Drawer component like ...

Linux web server blocking requests across different domains, even with correct Access-Control-Allow-Origin headers set

I am facing an issue with my Ubuntu web server running a React app. There are two files on the server that handle requests made by the website, but for some reason, clients are unable to make requests to the server. Server.js: const express = require(&apos ...

Twice within a controller, alert is displayed in AngulasJS, OnsenUI, and Phonegap

I'm currently developing a mobile application using AngularJS, OnsenUI, and PhoneGap to package it for Android devices. However, I've encountered a strange issue where an alert box pops up twice when the application is run as a new process. I&ap ...

What is the best way to pass the "getjson" capability from one function to another in a seamless manner?

Currently, I am dealing with a situation where a getjson call is used to retrieve a large amount of data. However, I find myself constantly having to check if the data is null or not. Here is an example: if (data.Height == "") { $(&ap ...

Is it possible for two node scripts running on the same machine to interfere with each other's execution

In the scenario where a parent node file (such as an express server) spawns child nodes that execute computationally intense tasks, will these children cause blocking for the parent process? ...

Transferring information using href in AngularJS

Within my controller for 'products', I am dealing with a substantial amount of data. The 'products' page contains a link structured similar to this: <td><a href="/#/getProducts/{{name}}/status" {{ ProductName }}</a>< ...

Enlarging the modal overlay

My Angular/Bootstrap app features a small text area within a modal window that often contains lengthy content exceeding the size of the textarea and modal itself. I am looking to incorporate a button within the modal window that, when clicked, opens a lar ...

How to manage multiple controllers for the same template in AngularJS?

I am facing a requirement where a single page needs to display a lot of different data, all within one vertical-scrolling page. To manage this, I have implemented collapsible divs on the page controlled by ng-if to efficiently handle the DOM elements. In ...

Tips for accessing a DOM element's ::before content using JavaScript

Is there a way to retrieve the content of a DOM element's ::before pseudo-element that was applied using CSS3? I've attempted several methods without success, and I'm feeling very confused! // https://rollbar.com/docs/ const links = docum ...

Testing the mongoose.connect callback method in Jest: A step-by-step guide

Currently working on a new Express application and utilizing Jest as the testing framework. All sections of code have been successfully covered, except for the callback of the mongoose.connect method: I attempted to spy on the connect method of the mongo ...

The catch block is triggered when the dispatch function is called within the try block

It's strange how the code below works perfectly without any errors and records a response once the loginHandler() function is triggered. However, when I include the dispatch function inside the try block after receiving the response, the catch block e ...

Enhance the Header component by incorporating a logout button that seamlessly navigates with the NextJS App

Currently, I am utilizing NextJS 14 with App router alongside Spring Boot on the backend. Within my application, I have both public and private routes set up. For the private routes, users are required to log in through a designated login page. Upon succes ...

When the update button is clicked, the textfield is hidden; it reappears upon refreshing the page

Our marketplace multi-vendor site on Magento allows sellers to list their products for sale. The frontend displays the price using the following code: Phtml <input onFocus="showPriceCancel('<?php echo $products->getId(); ?>');" clas ...

Exploring the best practices for organizing logic within Node.js Express routes

I'm currently utilizing the https://github.com/diegohaz/rest/ boilerplate, but I am unsure about the best practice for implementing logic such as QR code generation and additional validation. My initial thought was to include validation and password ...

Changing or toggling the visibility of links once the week is finished

I have a total of 4 links available, but I want to display only one link at a time, highlighting a different lunch option every week. Once all 4 weeks have passed, the first lunch menu will be shown again, starting from Monday. <div class="wrapper& ...

The issue arises with the Google Map marker failing to function correctly when pulling data

I've recently started learning Google Maps. It's interesting that markers work and are displayed when statically declared, but not when retrieved from a database. // var markers = [[15.054419, 120.664785, 'Device1'], [15.048203, 120.69 ...

Troublesome button appearance

I set up two sections to gather user information using buttons. My goal is for the button styles to change when clicked, making it clear to users which option they have selected, even if they switch between sections. However, I encountered an issue where ...

Is there a way to bring to life the addClass() and removeClass() jQuery functions through animation?

I am currently developing a website and I want to be able to toggle the visibility of sections by using the ".hidden" bootstrap class within click events. Here is the basic code snippet: $('selector').click(function(){ $('*part-to-hi ...