What is the best way to implement callbacks on functions triggered by ng-click in Angular?

I'm facing an issue with my email code where it doesn't finish after the function processing its data is completed. It's triggered by NG-click on a button, but none of the usual callback methods seem to be effective.

In Angular, post requests are sent to my express server for mailing purposes.

function processQuote() {
  $http({
    method  : 'POST',
    url     : '/send' ,
    data    : mailJson,
    headers: { 'Content-type': 'application/json' }
  }).success(function(data){
    console.log('success!');
  }).error(function(err,data){
    console.log(err);
  }); 
};  

This function loops through a mixed object/array table and generates a mailJson array that will be used for sending emails.

$scope.calculateAll = function(callback){
  var mailJson = [];
  var amount = 0;
  $scope.contact.totalQuote = 0;

  for (var i = 0; i < $scope.customers.length; i++) {
    if( $scope.customers[i].area != 0) {
      $scope.customers[i].total = parseInt($scope.customers[i].area, 10) * parseInt($scope.customers[i].price, 10);
      $scope.contact.totalQuote += parseInt($scope.customers[i].total);
      mailJson.push($scope.customers[i]);
    }
  }
  mailJson.unshift($scope.contact);
  callback(mailJson);
};

Lastly, here is the HTML snippet with ng-click functionality to trigger the process.

<button type="button" ng-click="calculateAll(processform)" class="btn btn-primary">Submit</button>

Answer №1

Your question may have been a bit confusing, but it seems like you are asking how to execute block code after receiving a response.

When using $http, it returns a deferred promise. To achieve this, you can create a function like:

function processQuote() {
  var promise = $http({
    method: 'POST',
    url: '/send',
    data: mailJson,
    headers: {
      'Content-type': 'application/json'
    }
  });
  return promise;
};

To run code after receiving a response in your controller, you can do the following:

processQuote().then(function(){
  // Code that should run after receiving a response goes here
});

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

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

Transform JSON array containing identical key-value pairs

My array is structured as follows: [ { "time": "2017-09-14 02:44 AM", "artist": "Sam", "message": "message 1", "days": 0 }, { "time": "2017-09-14 02:44 AM", " ...

extract individual components from the google books api

It has been quite a while since I last dabbled in JavaScript, so I decided to embark on a project creating a "bookcase" to organize the books I have read and those I still want to read. One challenge I encountered was figuring out how to separate the eleme ...

Is there a way to insert an attribute in HTML without simply appending it to the end of the tag?

I've been working on incorporating the code snippet below that I found in an angularjs table sort function. In the code, you can see the ts attributes being added to the html. However, this method is not suitable for hosting on Salesforce. Can anyone ...

Create a global base URL variable within the Axios plugin for Vue

As I work on my Vue.js project, I've successfully implemented a plugin for Axios following the guidelines provided here. This allows Axios to be utilized globally within the project. The key snippets of code in my project are as follows: in src/plugi ...

What is the best way to make the Nav bar overlap instead of shifting content to the right?

Is there a way to open the nav bar and have it overlap on the right without pushing content to the right? I tried experimenting with position and z-index, but it didn't work. Thank you! Link <div id="mySidebar" class="sidebar" ...

Clicking on a single checkbox causes the entire input to become deactivated due to the way the system is

I'm encountering a puzzling issue that has me feeling like I know the solution, yet I don't. I set "State" to [checked]. The problem arises when, upon turning it into a map and clicking just one checkbox, the entire selection is clicked. To addre ...

What is the best way to display a <div> depending on the screen size in React JS using a global variable, without utilizing state management?

I am attempting to display a message based on the screen resolution in ReactJS. I am utilizing a function component and trying to accomplish this without using state, by using a global variable. const isDesktop = window.innerWidth; {isDesktop > 768 ? ...

Automatically populate the options of a dropdown menu using jQuery

I am a beginner in the world of Javascript, JSON, and jQuery. I am seeking some guidance as I navigate through this new territory. On my JSP page, there is a drop down list that needs to be populated with content when the page loads. To achieve this, I hav ...

Is it possible to implement a "load more" feature with JSON data using the getJSON method?

Currently, I am working on the task of extracting objects from a JSON file and arranging them in a grid layout similar to masonry using Salvattore. While I successfully utilized this helpful tutorial to retrieve the data, my next challenge is to implement ...

The ID value did not pick up the number 0 when passed to the next blade after the initial reading

When passing an ID value to another blade file, I encountered an issue where the other blade file did not read the number 0 at the beginning. For example, if I pass the value of 006, when I console log the value in the other blade view, it only shows 6. H ...

Issues encountered with the performance of a Laravel Vue.js application

I am encountering a recurring issue when trying to run new applications that combine Laravel with Vue.js. This problem persists whether I am working on a partially developed app or starting from scratch with a fresh Laravel installation. Upon setting up La ...

How do I implement an onClick event for an antd message component?

I have a question and I'm hoping for some help. Here is the code snippet in question: const [msgTimer, setMsgTimer] = useState(5); message.error('some error msg', msgTimer); In the antd documentation, the message component has an onClic ...

Importing text data from a text file in Java or jQuery without the need for a web server

I've attempted to utilize both the jQuery.Get() and $.Get() methods for this task, but they don't seem to be working as expected. <head> <script type="text/javascript" src="jquery-2.1.3.min.js" > </script> <script lang ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Using angularjs to include content from other files is known as

As I delve into the concept of creating directives in AngularJS, I am faced with the imminent end of Angular 1.x and the rise of Angular 2.x. The shift seems daunting, but I am determined to bridge this gap seamlessly. In my quest for clarity, I stumbled ...

Applying unique textures to individual sides in Three.js

Here is the code for my textured cube: const textureLoader: TextureLoader = new TextureLoader(); const textureArray: MeshBasicMaterial[] = [ new MeshBasicMaterial({ map: textureLoader.load("./model/front.jpeg") }), new MeshBasicMaterial({ map ...

Create a smooth animation of scaling horizontally in Framer Motion while ensuring that the scale of the children elements

Framer motion 4 has deprecated the use of useInvertedScale(). The new recommendation is to use the layout prop, but it doesn't seem to achieve the same effect for me. I'm attempting to scaleX a parent div without affecting the scale of its childr ...

JavaScript Automation Script for QuickTime Screen Recording

Recently, I've been working on a JavaScript Automation script to record my screen on my Mac. However, I encountered an issue with the API when it reaches the line doc.close(). QuickTime would hang indefinitely and eventually my Script Editor would tim ...

JavaScript, AJAX rapid iteration

I am working with some ajax code: $(document).ready( function() { $("#button1").click( function() { $.ajax({ type: "POST", url: "update.php", }); }); }); In my HTML code, I have 200 buttons. How can I ...