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

"Discover the latest feature in the new Angular router: automatic scrolling functionality

The old ui-router and 1.4 angular router used to support autoscroll="true" to automatically scroll the page to the top when navigating to another route. Is there a way to achieve this with the latest new angular router? It seems like ng-outlet does not ha ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

Why is it that my website in React crashes when I type rapidly in the TextField component?

Whenever I input text quickly into the TextField in my app, it causes my website to crash and display a blank white screen. Below is the snippet of code causing the problem: TextField Code: <TextField label="Item name" ...

JavaScript can be used to create a fullscreen experience without any toolbars, scrollbars, and the like, without having

Is there a way for me to expand the current window I am using to fullscreen mode and eliminate all toolbars? ...

can you explain the concept of a backing instance in react?

Although the concept of a "backing instance" is frequently mentioned in React documentation, I found it difficult to grasp its meaning. According to the React docs: In order to interact with the browser, you need a reference to a DOM node. By attaching ...

Determining the ideal scenario for utilizing a nested array as opposed to employing a distinct collection

I'm trying to determine the best design approach for using mongoose with dbref in my project. Option 1: var user = mongoose.Schema({ name: 'string' }); var eventSchema = mongoose.Schema({ title: 'string', propietary_ ...

What is the best method for excluding past dates in the Ui calendar?

As a beginner with Ui calendar, I am seeking guidance on how to prevent users from selecting or interacting with previous dates in Ui-calendar using angularjs. While the Eventdrop, EventResize, and eventclick features are functioning properly for me, it ...

What steps can I take to refactor a portion of the component using React hooks?

I am trying to rewrite the life cycle methods in hooks but I am facing some issues. It seems like the component is not behaving as expected. How can I correct this? Can you provide guidance on how to properly rewrite it? useEffect(() => { updateUs ...

Transferring data between JavaScript and PHP

Is there a way to transfer data from JavaScript to PHP when a button is clicked? For instance, can the getdate() function's result be sent to PHP? This transferred value will then be utilized for database manipulation. ...

Dealing with redirecting to the login page in Angular

I recently started working with Angular and I feel completely lost. My initial task involves making a simple Rest-GET request, but the destination is located behind an external login page. This results in my request being redirected to the external page a ...

Expressjs route encountering issue with imported database function failing to return a value

Currently, I am in the process of creating a REST API using Expressjs. Initially, all routes were integrated into one main file. However, I have now separated these routes, database connection, and database methods into their individual files. login-db.js ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

Implement lazy loading for scripts in Next JS

Currently working on a project with Next JS and focusing on optimizations through Google's Page Speed Insights tool. One major performance issue identified is the presence of 3rd party scripts, specifically the Google Tag script (which includes Google ...

Inquiries about utilizing setTimeout with backbone.js and effectively managing timeouts

One of the questions I have is related to clearing timeouts using clearTimeout(content.idTimeout) for a specific idTiemout. But how can I clear all timeouts at once? Here is the model I am working with: var ContentModel = Backbone.Model.extend({ URL: "htt ...

Eradicate white space in a JavaScript code

Calling all JS programmers! Here's a challenge for you, check out this demo: https://codepen.io/gschier/pen/jkivt I'm looking to tweak 'The pen is simple.' to be 'The pen issimple.' by removing the extra space after 'is& ...

Using Jquery to iterate through a dynamic list of elements

Currently, I am exploring the idea of creating a forEach loop that can handle an unspecified number of elements. The goal is to randomly select one element, perform XYZ actions on it, make it visible, and then eliminate it from consideration. This process ...

Learn how to pass an id from the query parameters to the getInitialProps function in Next.js

Looking to create a basic website that displays content from a database? Utilizing the getInitialProps function from Next.js documentation can help with server-side rendering: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialpr ...

When taking a vertical picture on my iPhone, my Vue component does not function properly

Having trouble with displaying recently uploaded images on a form. If the image is taken from a phone, it may have an exif property that browsers do not handle correctly, causing the picture to appear flipped or sideways. Upside down photo To fix this is ...

Adding two comparable Objects in Javascript / vuejs

I have two objects and I want to add the values of each key separately with another object. Here's an example: CharacterStats: { a: 0, b: 2, c: 0, d: 0 } ItemStats: { a: 0, b: -1, c: 4, d: 0 } The expected result is: CharacterStats: { a: 0, b: 1, c: ...

Encountering difficulties while attempting to delete with a router.delete command - receiving a 404 not

Within my application, I am passing the request parameter 'id' in the router.delete method and communicating it with the Vuex service. However, when triggering the action, an API call is made but it results in a 404 error indicating "not found" a ...