Ways to retrieve a variable from outside of a function

I am in need of sending the following batch data to the database, but I am facing difficulties in including the course_id along with the batchData. Currently, I am retrieving the course_id from another service that fetches data from a course table. I am unable to access response.data.data[0]._id outside the function as it is a local variable. Is there any way to bind the course_id with batchData object?


app.controller('batch_add', function($scope, $http) {
    $http.get("/courses/getall")
    .then(function(response) {
            if (response.data.length == 0) {
                $scope.items = [{ course_name: "No data", course_desc: "No data", course_fees: "No data" }];
            } else {
                $scope.items = response.data.data;
                var course_name_items = []
                for (var i = 0; i < $scope.items.length; i++) {
                  course_name_items.push($scope.items[i].course_name)
                }
                $scope.course_items = course_name_items;
            }
        });

    $scope.batch_status_items = ['Pending', 'Running', 'Finished', 'Canceled' ]

    $scope.batchData={};
    $scope.login =  {"batchData" : $scope.batchData};
    $scope.submitForm = function() {
    $scope.login =  {"batchData" : $scope.batchData};
    $scope.fail = false;
        $http({
            method  : 'POST',
            url: 'batches/add',
            data    : $scope.login
    })
        .success(function(data) {
            if (data.success == true) {
                $scope.fail = true;
                $scope.success = true;
                $scope.success_message = data.message;
                var courseName = $scope.batchData.course_name;
                $http.get("/courses/search/"+courseName)
                .then(function(response) {
                        if (response.data.length == 0) {
                          console.log("error");
                        } else {
                            $scope.batchData.course_id= response.data.data[0]._id

                        }
                    });
                        toastr.options = {"positionClass": "toast-bottom-right"}
                        Command: toastr["success"]("A new batch has been added!")
                } else {
                    $scope.fail = true;
                    $scope.success = false;
                    $scope.error_message = data.message;
                    console.log($scope.success_message);
                   //  toastr.error('Something went wrong.', 'Ooops!')
                }                      
          });
$scope.batchData.course_id = response.data.data[0]._id
        };
    });

Answer №1

Have you considered retrieving the course ID before sending it to the database with batchData?

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

Storing a temporary value within an ng-repeat iteration in AngularJS

A unique and interesting query arises when dealing with random value generation. Here is a snippet of code that showcases how to achieve this: function randomize() { return function (input) { if (input !== null && input !== undefined & ...

Need a module from the main directory

Imagine having these folders: 'C:\\src' // Main directory. 'C:\\src\\inner1' // Contains 'a.js' 'C:\\src\\inner2\\innermost' // Contains 'b.js' ...

What is the best way to split a semicircular border radius in two equal parts?

Is there a way to halve the yellow line or remove it from above the red box, while keeping it below? Can this be achieved using just HTML and CSS, or is JavaScript necessary? * { margin: 0; padding: 0; box-sizing: border-box; } body { height: 1 ...

displaying a specific section depending on the radio button chosen

I am dynamically creating radio buttons using ng-repeat in my code snippet below: <input type="radio" ng-repeat="i in items" name="myRadio{{$index}}" value="{{i.val}}" /> Currently, this code generates 2 radio buttons. I would like to display a spe ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...

In JavaScript, if you check for the existence of a key in an object, it

Recently, I ran into an issue with an undefined error when trying to access a value in a JavaScript object key. I retrieved arrays of objects using the mongoose.find().exec() callback and then checked each object for a specific key. Here is an example obj ...

JavaScript 'await' throws error 'then is not defined'

Just starting out with async programming and I've noticed a common issue in similar threads - the problem of not returning anything. However, in my case, I am facing a different error message 'Cannot read property 'then' of undefined&ap ...

What could be causing my state not to change in Nextjs even though I followed the quick start guide for Easy Peasy?

I recently encountered an issue while trying to implement easy peasy for global state management in my nextjs app. The problem I faced was that the state would only update when I changed pages, which seemed odd. To better understand what was going on, I de ...

Exploring the Vanilla JavaScript alternative to the jQuery.each() function

$.fn.slideUpTransition = function() { return this.each(function() { var $el = $(this); $el.css("max-height", "0"); $el.addClass("height-transition-hidden"); }); }; When utiliz ...

What sets returning a promise from async or a regular function apart?

I have been pondering whether the async keyword is redundant when simply returning a promise for some time now. Let's take a look at this example: async function thePromise() { const v = await Inner(); return v+1; } async function wrapper() ...

Conflict arising from duplicated directive names in AngularJS

Hey there, I've got a question for the experts. How can I prevent conflicts with directive names when using external modules? Right now, I'm utilizing the angular bootstrap module, but I also downloaded another module specifically for its carouse ...

Retrieve all form data using the ng-click directive in AngularJS

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script> <div ng-app="myApp"> <div class="container" ng-controller="CtrlList"> <div class="row"> <div ng-repeat="x ...

Utilizing Electron's <webview> feature to display push notification count in the title

I'm currently working on a Windows app using Electron's webViewTag to integrate WhatsApp Web. While I have successfully implemented desktop toast notifications, I am curious if it is possible to display a notification count in the title bar of my ...

Unable to disable background color for droppable element

For my project, I am working with two div boxes. My goal is to make it so that when I drag and drop box002 into another div box001, the background color of box001 should change to none. I have attempted to achieve this functionality using jQuery without s ...

How to display JSON containing nested objects in AngularJS using the ng-repeat directive

Hey everyone, I have this JSON external file that I need help with: { "success":true, "errors":[ ], "objects":[ { "cod":"8211300", "descricao":"Serviços advocatícios" }, // more objects here... ] } In ...

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

Having issues with inline conditional statements in Angular 5

There is a minor issue that I've been struggling to understand... so In my code, I have an inline if statement like this: <button *ngIf="item?.fields?.assetType !== 'tool' || item?.fields?.assetType !== 'questions'">NEXT< ...

What is the best way to display only the current != wanted lines when using "npm outdated"?

Whenever I input npm outdated, it shows a similar output like this: Package Current Wanted Latest Location columnify 1.1.0 1.1.0 1.2.1 /usr/local/lib > npm > columnify cmd-shim 1.1.2 1.1.2 2.0.0 /usr/local/lib & ...

What's causing jQuery to make the entire page malfunction?

I am experiencing an issue where a function is not recognized as being in scope when I have a reference to jQuery defined. Oddly enough, if I comment out that reference, the function call works just fine. I have other pages set up the same way with jQuer ...

What are some effective design principles for creating REST APIs in expressjs?

To streamline my code organization, I made the decision to create a methods folder. Within this folder, I store individual JavaScript files for each URL endpoint (such as website.com/billings). //expressJS configuration... const billings = require('. ...