Obtain an indeterminate value from a variable

My situation involves a dynamic variable assigned from a service, requiring a real-time calculator to update another variable using its value.

Below is the relevant code snippet:

$scope.getSubTotalSCTax = function(){
    TableService.checkOut('SubTotal', $scope.DetailMeja.finCheckInID)
    .then(function(response){
        console.log(response);
        $ionicLoading.hide();
        $scope.checkOut = {
            SubTotal: response.SubTotal,
            TaxPercentage: response.TaxPercentage,
            ServiceChargePercentage: response.SCPercentage,
        };
    }, function(err){
        console.log(err);
    })
};
$scope.getSubTotalSCTax();

$scope.checkOut.ServiceCharge = $scope.checkOut.SubTotal * $scope.checkOut.ServiceChargePercentage / 100;
$scope.checkOut.Tax = $scope.checkOut.SubTotal * $scope.checkOut.TaxPercentage / 100;

However, an error stating

TypeError: Cannot read property 'SubTotal' of undefined
occurs at the line
$scope.checkOut.ServiceCharge = $scope.checkOut.SubTotal * $scope.checkOut.ServiceChargePercentage / 100;

*UPDATE : I have included an input type="text" for both Tax Percentage and Service Charge Percentage. These values need to trigger a recalculation each time they are changed.

*UPDATE2 : The recalculation issue has been resolved by utilizing the ng-change event to call a function that runs the recalculate process.

Answer №1

It's important to remember that the TableService.checkout function runs asynchronously. This means that the then callback won't be executed until after the rest of your code has finished evaluating.

To handle this, make sure to return the promise from the function.

$scope.calculateSubTotalAndTax = function(){
  var promise = TableService.checkOut('SubTotal',$scope.tableID);

  promise.then(function(response){
    // ...
  });

  return promise;
};

Then, when you call the method, chain another then onto the promise to ensure proper execution order.

$scope.calculateSubTotalAndTax().then(function() {
  $scope.tableServiceCharge = $scope.tableSubTotal * $scope.serviceChargePercentage / 100;
  $scope.tableTax = $scope.tableSubTotal * $scope.taxPercentage / 100;
});

Answer №2

function calculateTaxAndServiceCharge() {
    return TableService.checkOut('SubTotal', $scope.DetailMeja.finCheckInID)
};

calculateTaxAndServiceCharge().then(function(response) {
    console.log(response);
    $ionicLoading.hide();
    $scope.checkOut.ServiceCharge = response.SubTotal * response.SCPercentage / 100;
    $scope.checkOut.Tax = response.SubTotal * response.TaxPercentage / 100;

}, function(err) {
    console.log(err);
})

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

What is the best way to pass JSON data into a JavaScript function?

As a beginner in javascript, I have been struggling to find a solution for my problem for a week. The code example I am working with is shown below (all within an HTML page in the head tag) //example function 1 function randomString(len, charSet) { ...

Creating dynamic scroll animations for sidebar navigation in a single-page website with anchor links

I need help creating a seamless transition between anchor points on a single page, while keeping a fixed navigation menu that highlights the active section. As a novice, I am unsure how to incorporate "( document.body ).animate" or any other necessary code ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

Using various colors to highlight specific sections of a letter or number

I am striving to recreate the unique image shown below, particularly interested in achieving the multi-colored effect on the numbers. This aspect of having different colors for parts of the number is intriguing and I would love to learn how it's done. ...

What is the best way to utilize ng-if to conceal a component in AngularJS when a button in a separate component is clicked?

I am facing a challenge with two child components within a parent component. My goal is to hide component1 when a button in component2 is clicked. Below is an illustration of the current code I am handling: Parent Component HTML: <div ng-app='ap ...

Display the jQuery validation message in the final td cell of the table

JavaScript Animation Library rules:{ gender: { required: true }, }, messages:{ gender: { required: "Please indicate your gender" }, }, errorPlacement: function (error, element) { if (element.attr("type") == "radio") { ...

ES6 Generators: lack of informative stack trace when using iterator.throw(err)

The ES6 approach: iterator.throw(err) is often explained as inserting an exception as if it happened at the yield statement within the generator. The challenge lies in the fact that the stack trace of this exception does not include any information about t ...

Performance problems with Ionic ion-slides due to excessive method calls

Encountering an issue with the ion-slides component where a method within my ion-slide is being called excessively, causing significant slowdown. Surprisingly, the method is triggered 900 times initially (despite showing only 100 slides) and each slight sw ...

Error: Cannot access 'muiName' property as it is undefined

i am trying to display the elements of an array within a custom card component in a grid layout. However, when the page loads it freezes and the console shows "Uncaught TypeError: Cannot read property 'muiName' of undefined" custom car ...

Implementing Ideone API functionality on Codeigniter with the use of ajax, javascript, and soapclient

I am new to using Codeigniter and I apologize if my question is basic. I found some code on this site: Working with IDE One API (Full project code available here) and I'm attempting to incorporate it into Codeigniter. I have been able to get it worki ...

Clicking activates Semantic UI's dropdown function with the onClick method

I am experiencing an issue with the dropdown functionality on my website. Everything works fine until I add onClick() to the Semantic UI component. It seems like there are some built-in functions for handling onClick() within Semantic UI, so when I impleme ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

Converting timestamps: Retrieve day, date, hour, minutes, etc. without utilizing the "new Date()" function

Currently developing a web-app and faced with the challenge of displaying items in a list correctly. I am working on converting the timestamp attached to each item into a readable format. For instance, 1475842129770 is transformed into Friday, 07.09.2016 ...

Tips for making the background image fit perfectly within a div element

I have a calendar div that I want to customize with a background image and text. How can I achieve this? Here is my code: .calenderArrivalDiv{ margin-top: 15%; margin-bottom: 1%; background-image: url("im ...

Rotating an input 90 degrees within a div for unique positioning

I used JavaScript to make an input range vertical, like so: var range_pitch = document.createElement("input"); range_pitch.setAttribute("type", "range"); range_pitch.style.webkitTransform = "rotate(90deg)"; range_pitch.style.mozTransform = "rotate(90deg)" ...

Try utilizing querySelectorAll() to target the second item in the list

As I delve into the world of HTML and JS, I came across the document.querySelectorAll() API. It allows me to target document.querySelectorAll('#example-container li:first-child'); to select the first child within a list with the ID 'exampl ...

What is the best way to track all method calls in a node.js application without cluttering the code with debug statements

How can I automatically log the user_id and method name of every method called within a javascript class without adding logger statements to each method? This would allow me to easily track and grep for individual user activity like in the example below: ...

There was an issue encountered when trying to call a PHP file within an HTML table using Ajax and data.html

For a small project, I have various news items that need to be included from the "news_all.php" file into table data within the "dashboard.php" file. Due to the predefined root structure restrictions, using include('news.php') is not an option. I ...

Vuejs allows objects to trigger the execution of methods through elements

My goal is to utilize a function in order to individually set the content of table cells. In this specific scenario, I aim to enclose the status with the <strong> - Tag (I refrain from modifying the template directly because it is stored within a com ...

Is it Unwise to Depend on Props within the useReducer Hook?

Within my App() component, I utilize props named data. This particular component relies on a useReducer hook to manage its state. The reducer function is responsible for determining when to display or hide specific data based on the state. Additionally, it ...