What happens when AngularJS returns an empty object after just one click?

This is a function that I call on ng-click.

HTML

<div class="col-md-offset-10">
    <div class="form-group">
    <a class="btn btn-default" ng-click="schedule ()">Add</a>
    </div>
</div>

JS

$scope.scheduleid={};
var inc=0;

$scope.schedule = function ()
{   
    inc += 1;
    console.log($scope.from);

    console.log ($scope.dateObj);
    if (inc == 1)
    {
        var schedule = {}
        schedule._type = "Schedule";

        console.log($scope.dateObj);
        var insertSchedule = BasicJSONCreator.basicEdit ();
        insertSchedule.Calls[0].Arguments = [];
        insertSchedule.Calls[0].Arguments[0] = schedule;

        httpRequester.async (insertSchedule).then (function (data) {

        console.log(data.data.ReturnValues[0].scheduleID);
        $scope.scheduleid=data.data.ReturnValues[0] //This gets a response from my database
        console.log($scope.scheduleid ); // retrieves data from the database

        });
    }
    $scope.getData();
}

This function is meant to retrieve results from $scope.scheduleid, but there seems to be an issue here. When I click once, $scope.scheduleid is empty. However, with two or more clicks, $scope.scheduleid is not empty and contains data. Why is it empty on the first click?

$scope.getData=function()
{
    console.log($scope.scheduleid)
    // The object is empty after one click, but contains data after two or more clicks
}

Answer №1

It seems the issue lies within your HTTP request handling process. When you trigger the function with a click, the call is initiated but continues running while your function moves forward.

As a result, the object appears empty after the first click. Only after the HTTP request is completed - possibly on the second click - will you receive the data. To resolve this, it is essential to wait for the HTTP call to finish before proceeding further. You can accomplish this using methods like $timeout or explore solutions suggested in sources such as this resource.

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

Partial data is being received from the Ajax call

I currently have a textarea and a button on my webpage <textarea id="xxx" class="myTextArea" name="Text1" cols="40" rows="15">@ViewData["translation"]</textarea> <input type="button" id="convert-btn" class="btn btn-primary" value="Convert t ...

The search bar is updated with the page number that is chosen

I have been working on creating a search engine using elasticsearch and PHP. Initially, the live data search functionality with AJAX was functioning properly. However, when I incorporated pagination, the search query got replaced by the page number. Conseq ...

"Create a dynamic entrance and exit effect with Tailwind CSS sliding in and out from

My goal is to create a smooth sliding animation for this div that displays details of a clicked project, transitioning in and out from the right side. This is my attempt using Tailwind CSS: {selectedProject !== null && ( <div classNam ...

Changing text content of an element with dynamic formatting

When a link is clicked on, I want to dynamically set the text. Here is the current code: <a href="www.somelinkhere.com" onclick="getElementById('setText').innerHTML='text to replace'" target="someIFrame" ...

Is there any issue that you can spot with this js / jQuery code?

Presented below is a script that prompts the user to confirm clicking a button based on a system setting. The system setting is saved in a hidden field established from the code-behind. Markup: <asp:HiddenField ID="hfConfirmOnApproval" runat="server" ...

Ways to Verify the Existence of a Value in an Array Using JavaScript

In my Laravel blade file, I have an array that I am accessing in JavaScript like this: var data = {!! json_encode($data) !!}; When I check the console, the variable is displayed as seen here: variable data console print Additionally, I'm retrieving ...

The onClick event for "history.go(0)" is functional in Internet Explorer, but it does not work in Mozilla Firefox. What can be done to address this problem specifically for Mozilla browser?

After experimenting with different browser compatibility, I have discovered a way to clear all fields when clicking the "New" button. By using the code onClick="history.go(0)", the fields are successfully emptied in IE but unfortunately fail in Mozilla. ...

Guide on inserting data from an array into a Bootstrap dropdown menu with a search feature

Utilizing the bootstrap combobox with search functionality has been successful when using static options, as shown below: <form role="form"> <div class="form-group"> <label>Select options</label> <select class="co ...

Issue with npm version: 'find_dp0' is not a valid command

Hello, I have a small node application and encountered an issue while running a test. The error message displayed is as follows: 'find_dp0' is not recognized as an internal or external command, operable program or batch file. It seems to be re ...

Different responsibilities assigned to a single user in PHP

I'm thinking about setting up a back office for my website. The issue I'm facing is that if a user has multiple roles, I want them to be able to choose which role they want to work with. However, I've been struggling to figure out how to imp ...

Error: The function (0, _context_stateContext__WEBPACK_IMPORTED_MODULE_4__.useStateContext) is not of type TypeError

I have been working on setting up a useContext() for an online store to share data across all components and manage product quantities. However, I've hit a snag while trying to import the context(). Everything was running smoothly until I added this p ...

Cover the entire screen with numerous DIV elements

Situation: I am currently tackling a web design project that involves filling the entire screen with 60px x 60px DIVs. These DIVs act as tiles on a virtual wall, each changing color randomly when hovered over. Issue: The challenge arises when the monitor ...

Website: Showcase Opentok using a Picture-in-Picture design

Currently, I am utilizing Opentok.js and my objective is to showcase both the subscriber and publisher within a Picture-in-Picture layout. I require this setup to be responsive and retain its aspect ratio when resizing the window. Additionally, I need gu ...

How come the variable is not being passed to the HTML article within the function?

I'm struggling to pass a variable from a function to an article. Despite successfully displaying the variable in an alert box, I can't seem to get it to show up in the article content. What am I missing? After confirming that "a" contains the co ...

What is the best way to trigger a modal on Bootstrap using a JavaScript/jQuery function?

I encountered an issue while attempting to call a bootstrap modal using a simple button or link, which may be due to a conflict with my select2 plugin (although I am uncertain). I tried appending the button to the select2 dropdown but it doesn't seem ...

Remembering position in JSP using Java Beans

In my "Web Engineering" assignment, I am tasked with developing a Web Application game using JSP, Servlets, and Java Beans. The game mechanics are already in place with the Servlet controlling the algorithms, JSP handling the Model/View, and Beans managing ...

Retrieve the DOM variable before it undergoes changes upon clicking the redirect button

I have been struggling for a long time to figure out how to maintain variables between page refreshes and different pages within a single browser session opened using Selenium in Python. Unfortunately, I have tried storing variables in localStorage, sessio ...

What is the best way to set up localStorage with a multi-dimensional array

I am struggling with modifying my local storage and it's taking up a lot of my time. Initially, I set it up like this: localStorage.setItem('example','{"data": []}'); It was working fine, but now I need to structure it like the ...

What is the best way to retrieve unique elements from a mongoose database based on specific criteria?

In my Node.JS project, I have a model called Activity with certain attributes defined as follows: const Activity = mongoose.Schema({ name: { type: String, require: [true, "A activity must have a name"] }, city: { ...

Troubles with Vue.js when retrieving URL data from API

How can I properly display multiple store URLs from an API in separate lines? Here is my vue code: <a v-bind:href=“storeUrl”> {{storeUrl}} </a> And here is my script: .... computed:{ storeUrl() { return this.games.store.map(({{url}}) => ...