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

selecting arrays within arrays according to their date values

With an array of 273 arrays, each containing data about a regular season NFL football game, I am looking to categorize the games by week. In total, there are 17 weeks in the NFL season that I want to represent using separate arrays. The format of my array ...

Can this functionality be accomplished using only HTML and CSS, without relying on JavaScript?

Image for the Question Is it possible to create a zoom functionality using only HTML and CSS, without relying on JavaScript? I need this feature for a specific project that doesn't support JavaScript. ...

What is the method for sending raw put data using the request npm package in a Node.js environment

How can I hit an API using the "require" npm package in Node? The API requires raw PUT data instead of PUT fields. Can anyone please guide me on how to achieve this using the request npm package? For example, here is the raw PUT data that needs to be sent ...

Unforeseen behavior in Ajax success callback

My unordered list contains a href link. Initially, only the welcome page is visible on page load. Upon clicking the list for the first time after page load, the desired results are displayed in the corresponding div as expected. The issue arises when swi ...

triggers an unexpected error in console.log

I need help with the following code: function printName(obj) { console.log(obj.name); } printName({ name: "myName" }); (function displayError(errorMsg){ console.log(errorMsg); })("Error"); However, when I try to run this code, I am encountering a T ...

Querying specific data from the API using unique identifiers

If the api.football-data.org/v1/competitions holds this data: { "_links": { "teams": { "href": "http://api.football-data.org/v1/competitions/444/teams" } }, "id": 444, "caption": "Campeonato Brasileiro da Série A", ...

What is the best way to retrieve the dimensions of a custom pop-up window from the user?

Currently, I am in the process of developing a website that allows users to input width and height parameters within an HTML file. The idea is to use JavaScript to take these user inputs and generate a pop-up window of a custom size based on the values pro ...

When a link is right-clicked, the window.opener property becomes null

Currently, I am utilizing the window.opener property in JavaScript to update the parent window from a child window. The parent window simply consists of a table with data and a link to open the child window. When the child window is launched, a JavaScript ...

Angular list with a repeating group of radio buttons

I have a set of 'options', which consists of the following: {Id: 1, Label: "option 1"}, {Id: 2, Label: "option 2"} Additionally, I have a list of 'products' structured as follows: {Id: 1, Name: "Name 1", Recommend: options[0]}, {Id: ...

"The Bootstrap framework in MVC is throwing an error message stating that '$.notify' is not recognized as

I'm having trouble getting a notify to show up when my ajax function completes successfully. I've checked my code and everything seems fine, but for some reason the notify isn't working as expected. When I checked the Chrome console, I found ...

Tips for retrieving an input value following a DOM insertion

Developing a function to inject HTML into the DOM following an AJAX call like this: The function for injecting HTML $.ajax({ type: "POST", url: base_url + "main/GetTheLastSeq" }) .done(function( msg1 ) { ...

knockout.js' $root leads to a page displaying nothing

Using the $root binding context is resulting in a blank page for me. Removing it allows the page to load properly. Causing blank page: <td><input data-bind="value: name" /></td> <td><select data-bind="options: $root.availableMe ...

I am currently dedicated to enhancing my background transitions and experimenting with creating smooth fade-ins

I'm almost done with my Weather Forecast page for the FCC challenge. However, I'm not satisfied with how the code for swapping the background works. It just doesn't feel right to me. Unfortunately, I can't figure out how to fix it. Addi ...

JavaScript can be utilized to generate an array containing duplicated phrases from a given text

Here's a simple concept: you enter text in a textarea, click "send," and receive a list of recurring phrases. When I say phrases, I mean sequences of two or more words that repeat. While I can identify single words, detecting these phrases is where I& ...

Registering the service worker resulted in an error stating "Undefined is not a function"

When attempting to register a service worker using default React code, I discovered that some users were encountering a `TypeError: undefined is not a function` on the line `.then(registration => {` inside the registerValidSW function. Although it works ...

Adjust the counter by increasing or decreasing based on the selection or deselection of tags

Currently, I am utilizing Next.js to manage a question form that consists of multiple questions with multiple answers. Users have the option to select one or multiple tags for each question. When a user selects one or more tags to answer a question, it sho ...

Guide on including a callback function in the renderCell columns of Material UI X Datagrid

When a button is clicked and the redux action is successful, I am trying to use a simple toast hook to display a message in the parent component where my Data grid is located. Can a callback be passed to utilize this hook from within the data grid? Here i ...

Select the default option and what occurs in the event of an HTTP connection

I am currently facing an issue with two aspects. Firstly, I am struggling to set a default option in my Select element. Despite using ng-model, it only displays a blank option at the moment: <select class="form-control" ng-model="pageSize"> ...

ReactJS Enhancements: Additional Selection Feature

Is there a way to access both {board.id} and {board.name} properties in my select value? I tried using example={board.name} but it didn't work. handleChange(event){ this.setState({value: event.target.value}); this.setState({examp ...

Utilizing external Cascading Style Sheets in AngularJS 1

Can an external CSS be applied to a component in AngularJS1? If yes, then how can it be done? I have only seen examples of applying inline css... ...