Angular JS was unable to show the complete sum of the row

I'm attempting to calculate the total of the Money In and Money Out columns. I have defined two functions to accomplish this, but instead of displaying the total at the bottom of the web page, it shows NaN. I'm confused about where I went wrong.

Below is the Angular JS code used:

@{
    Layout = null;
}

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http, $window) {
            $scope.IsVisible = false;
            $scope.Search = function () {
                var post = $http({
                    method: "GET",
                    url: "http://localhost:52098/HalifaxIISService.svc/TranscationDetails/" + encodeURIComponent($scope.Account_Number),
                    dataType: 'json',
                    headers: {
                        'Accept': 'application/json, text/javascript, */*; q=0.01',
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                });

                post.then(function (response) { 
                    var data = response.data; 
                    $scope.Customers = JSON.parse(data); 
                    $scope.IsVisible = true;
                }, function (err) {
                    $window.alert(err);
                });
            }

            $scope.grandTotal = function () {
                return $scope.Customers.reduce(function (previousTotal, m) {
                    return previousTotal + parseFloat(m.Deposit);
                }, 0); 
            }

            $scope.grandTotal1 = function () {
                return $scope.Customers.reduce(function (previousTotal, m) {
                    return previousTotal + parseFloat(m.Withdrawal);
                }, 0); 
            }
        });
    </script>

    <div ng-app="MyApp" ng-controller="MyController">
        Account Number:
        <input type="text" ng-model="Account_Number" />
        <input type="button" value="Submit" ng-click="Search()" />
        <hr />
        <table style="border: solid 2px Green; padding: 5px;" ng-show="IsVisible">
            <tr style="height: 30px; background-color: skyblue; color: maroon;">
                <th></th>
                <th>Account Number</th>
                 <th>Money In</th>
                <th>Date</th>
                 <th>Money Out</th>
                <th>Date</th>
                <th>Account Balance</th>
                <th></th>
                <th></th>

            </tr>
            <tbody ng-repeat="m in Customers">
                <tr style="height: 30px; background-color: skyblue; color: maroon;">
                    <td></td>
                    <td><span>{{m.Account_Number}}</span></td>
                     <td><span>{{m.Deposit| currency:"£"}}</span></td>
                    <td><span>{{m.Date}}</span></td>
                    <td><span>{{m.Withdrawal | currency:"£"}}</span></td>
                    <td><span>{{m.Date}}</span></td>
                    <td><span>{{m.Account_Balance| currency:"£"}}</span></td>

                </tr>


            </tbody>
            <table style="border: solid 2px Green; padding: 5px;" ng-show="IsVisible">
                <tr style="height: 30px; background-color: skyblue; color: maroon;">
                    <td>Total Money In:</td>

                    <td>{{grandTotal()}}</td>

                    <td>Total Money Out:</td>

                    <td>{{grandTotal1()}}</td>

                    <td>Account Balance:</td>

                    <td>{{m.Account_Balance| currency:"£"}}</td>

                </tr>
            </table>
        </table>

    </div>
</body>
</html>

Click here for a visual result of when I run the application: https://i.sstatic.net/8Ru1w.png

Answer №1

The issue here arises from nesting the total functions within the search function, resulting in the following script structure:

<script type="text/javascript>
  var app = angular.module('MyApp', [])
  app.controller('MyController', function ($scope, $http, $window) {
      $scope.IsVisible = false;
      $scope.Search = function () {
          var post = $http({
              method: "GET",
              url: "http://localhost:52098/HalifaxIISService.svc/TranscationDetails/" + encodeURIComponent($scope.Account_Number),
              dataType: 'json',
              headers: {
                  'Accept': 'application/json, text/javascript, */*; q=0.01',
                  'Content-Type': 'application/json; charset=utf-8'
              }
          });

          post.then(function (response) { // .success(function(data => .then(function(response
              var data = response.data; // extract data from resposne
              $scope.Customers = JSON.parse(data); // eval(data.d) => JSON.parse(data)
              $scope.IsVisible = true;
          }, function (err) {
              $window.alert(err);
              });
      }

      $scope.grandTotal = function () {
          return $scope.Customers.reduce(function (previousTotal, m) {
              return previousTotal + parseFloat(m.Deposit);
          }, 0); // Send in 0 as the default previousTotal 
      }

      $scope.grandTotal1 = function () {
          return $scope.Customers.reduce(function (previousTotal, m) {
              return previousTotal + parseFloat(m.Withdrawal);
          }, 0); // Send in 0 as the default previousTotal 
      }
  });
</script>

To address this, consider using ng-if instead of ng-show to avoid running the total functions and generating errors when no customer is found.

Below is a snippet with simulated data for demonstration purposes:

var app = angular.module('MyApp', []);

app.controller('MyController', function($scope, $http, $window) {
  $scope.IsVisible = false;
  $scope.Search = function() {
    $scope.Customers = [{
      Account_Number:17,
      Deposit: 10000,
      Withdrawal: 0,
      Account_Balance: 10000
    }, {
      Account_Number:17,
      Deposit: 0,
      Withdrawal: 2000,
      Account_Balance: 8000
    }, {
      Account_Number:17,
      Deposit: 1500,
      Withdrawal: 0,
      Account_Balance: 6500
    }];
    $scope.IsVisible = true;
  };
  $scope.grandTotal = function() {
    return $scope.Customers.reduce(function(previousTotal, m) {
      return previousTotal + parseFloat(m.Deposit);
    }, 0); // Send in 0 as the default previousTotal 
  };
  $scope.grandTotal1 = function() {
    return $scope.Customers.reduce(function(previousTotal, m) {
      return previousTotal + parseFloat(m.Withdrawal);
    }, 0); // Send in 0 as the default previousTotal 
  };
});
<!DOCTYPE html>
<html ng-app="MyApp">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.11" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MyController">

  <div>
    Account Number:
    <input type="text" ng-model="Account_Number" />
    <input type="button" value="Submit" ng-click="Search()" />
    <hr />
    <table style="border: solid 2px Green; padding: 5px;" ng-if="IsVisible">
      <tr style="height: 30px; background-color: skyblue; color: maroon;">
        <th></th>
        <th> Account Number</th>
        <th> Money In</th>
        <th>Date</th>
        <th> Money Out</th>
        <th>Date</th>
        <th>Account Balance</th>

        <th></th>
        <th></th>

      </tr>
      <tbody ng-repeat="m in Customers">
        <tr style="height: 30px; background-color: skyblue; color: maroon;">
          <td></td>
          <td><span>{{m.Account_Number}}</span></td>
          <td><span>{{m.Deposit| currency:"£"}}</span></td>
          <td><span>{{m.Date}}</span></td>

          <td><span>{{m.Withdrawal | currency:"£"}}</span></td>
          <td><span>{{m.Date}}</span></td>
          <td><span>{{m.Account_Balance| currency:"£"}}</span></td>

        </tr>
      </tbody>
    </table>
    <table style="border: solid 2px Green; padding: 5px;" ng-if="IsVisible">
      <tr style="height: 30px; background-color: skyblue; color: maroon;">
        <td>Total Money In:</td>

        <td>{{grandTotal()}}</td>

        <td>Total Money Out:</td>

        <td>{{grandTotal1()}}</td>

        <td>Account Balance:</td>

        <td>{{m.Account_Balance| currency:"£"}}</td>

      </tr>
    </table>
  </div>
</body>

</html>

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

Finding the Origin and Automatically Forwarding

I'm having an issue with my code. It's not functioning as expected. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml ...

Resolving the $rootScope:infdig infinite looping issue

I understand the concept of the infinite digest loop and how it occurs, but I am encountering an issue. You can see my code and problem demonstrated in this fiddle: http://jsfiddle.net/eS5e5/1/ If you check the console in the jsfiddle, you'll notice ...

Using the Django REST framework to serialize nested data and send nested JSON objects along with files via

What is the best method for sending a POST request with nested data, including files such as images, to django REST utilizing nested serializers? If we have the following JavaScript object: bookData: { title: 'Anne of Green Gables', cov ...

Utilize JavaScript to trigger a div pop-up directly beneath the input field

Here is the input box code: <input type='text' size='2' name='action_qty' onmouseup='showHideChangePopUp()'> Along with the pop-up div code: <div id='div_change_qty' name='div_change_qty&ap ...

The date format in AngularJS is not being displayed correctly according to the request

My goal is to retrieve the date in the format of dd/MM/yyyy and pass it along to my URI. However, I am encountering an issue where the date is not being passed in the requested format. Below is the snippet of my HTML code: <script type="text/ng-templat ...

Can an event be activated when a field in HTML5 is deemed valid?

Valid fields in HTML5 follow specific conventions, such as an type="email" needing to adhere to the email format. CSS provides a way to select valid fields using the pseudo-element: input:valid. Can we set up an event that triggers when the input becomes ...

Postman is showing an error when making a request using Express.js app.get()

Recently, I started working with Express.js and I am using Postman to test my API. When running the code below, I successfully retrieve all members from the object: // gets all members app.get('/api/members', (req, res) => { res.json(membe ...

Utilizing AngularJS ngResource: Ensuring Consistent Use of the Catch Function

Each time a server request using any $resource fails, I want to display the same alert message to my users. Currently, my code looks like this: function tryAgain() { alert("try again") } myResource.query().$promise.catch(tryAgain); myResource.update(...) ...

beforeprinting() and afterprinting() function counterparts for non-IE browsers

Is there a way to send information back to my database when a user prints a specific webpage, without relying on browser-specific functions like onbeforeprint() and onafterprint()? I'm open to using any combination of technologies (PHP, MySQL, JavaScr ...

I am trying to access the serial number data from an array of objects in ReactJS. Can anyone guide me

Is there a way to extract data from an array of objects, such as getting the serial number in ReactJS? In my current code snippet, I have an array called "number" with values [1, 2, 3]. My goal is to retrieve and display these numbers as a string like th ...

What is the process for converting an array of strings into a 2D array?

How can I transform the string ["0,1", "0,1", "1,2"] into an array of arrays like this: [[0,1], [0,1], [1,2]]? ...

Is there a jade plug-in available that enables manipulation using syntax similar to jQuery?

If I have a list of li elements and I want to use JavaScript to find an element with class X and modify some of its attributes, I know it can be done with regular JavaScript, but I'm unsure of how to select existing elements and manipulate them. Is th ...

Avoiding the insertion of duplicates in Angular 2 with Observables

My current issue involves a growing array each time I submit a post. It seems like the problem lies within the second observable where the user object gets updated with a new timestamp after each post submission. I have attempted to prevent duplicate entr ...

Ways to troubleshoot and verify values in PHP that are sent through AJAX

In my jQuery function, I am using AJAX to send values to a PHP file: $.ajax({ //make ajax request to cart_process.php url: "cart_process.php", type: "POST", dataType: "json", //expect json value from server data: { quantity: iqty, ...

Discover the best method for sending multiple API requests to Vuex store using Nuxt middleware

I am having trouble figuring out how to make multiple API calls to Vuex store from Nuxt middleware. I have successfully implemented it for a single API call, but I can't seem to get it working for multiple APIs. // middleware/log.js import axios fro ...

Can you explain the process of implementing a conditional render with three parts in React?

Currently, I am attempting to implement a conditional render but encountering some issues. Is it achievable? location: `${props.off_campus_location ? ( `${props.off_campus_location}` ) : ( `${props.campus_location.name}` ) : ( `${props.location_type}` )}` ...

Tips for ensuring the input value matches the data list and avoiding errors

I have successfully transformed an input element into a dropdown menu. However, I am experiencing an issue. If a user types something like 'foo' instead of selecting a month from my data-list, the input field and form still accept this value as ...

The function replace does not exist in t(…)trim

I encountered an error in my code that breaks the functionality when checked using console.log. var map = L.map('map').setView([0, 0], 2); <?php $classesForCountries = []; if (have_posts()) : while (have_posts()) : the_post(); ...

Decrease the jQuery version for a particular view exclusively

Imagine a scenario where I am utilizing jQuery version 1.10 in _Layout.cshtml, but need to downgrade to 1.7.2 for certain pages. Is there a way to achieve this without altering the Layout for these specific views? Can this be done at all? :) ...

When transitioning between two distinct Angular applications, AngularJS end-to-end tests experience delays

I've been facing a challenging issue: attempting to create end-to-end tests for a complex Angular application. The dilemma lies in the fact that the login screen is a separate entity from the main app. Initially, this was designed so that upon enterin ...