Find the variance between the sums of columns 3 and 5 using Angular

Is there a method to calculate the variance between column 3 and the last one in a table?

<body ng-app="Test">
  <section style="margin-top:80px">

    <h3>Plastic Calculator Form Version 2.0</h3>

    <div ng-controller="TestController as test" >
      <p>To date, 
        <strong><u># of people who pledged</u></strong>
        Earthlings have committed to reducing
           their single-use plastic waste from 
          <strong><u>{{ test.approve | sumByColumn: 'amount' }}</u>
          </strong> Items per year to <strong>
          <u>{{ test.approve | sumByColumn5: 'amount' }}</u>
        </strong>.
        That's a reduction of 
        <strong><u>{{ test.approve | sumByColumn4: 'reducedTotal' }}</u>
        </strong> per year!  Do your part.  Make a pledge!
      </p>
      <table class="table">
        <tr>
          <th>Single-Use Plastic Items</th>
          <th>Enter the Number You Use Per Week</th>
          <th>The Number You Use Per Year is:</th>
          <th>How Many Less Can You Use Per Week?</th>
          <th>Your Reduced Usage Per Year Would Be:</th>
        </tr>

        <tr ng-repeat="x in test.approve">
          <td> {{ x.name }} </td>
          <td> <input class="qty form-control" type="number"
                      ng-model="x.number" ng-change="sumByColumn3()" min="0"
                      restrict-to="[0-9]"/> 
          </td>
          <td ng-model="x.amount"> {{ x.number*x.amount }} </td>
          <td> <input class="qty form-control" type="number"
                      ng-model="x.reducedAmount" ng-change="sumByColumn2()"
                      min="0" restrict-to="[0-9]"/> 
          </td>
          <td ng-model="x.reducedTotal"> {{ x.reducedAmount*x.reducedTotal }}
          </td>
        </tr>
        <tr>
          <td>TOTALS</td>
          <td>{{ test.approve | sumByColumn3: 'number' }}</td>
          <td>{{ test.approve | sumByColumn: 'amount' }}</td>
          <td>{{ test.approve | sumByColumn2: 'reducedAmount' }}</td>
          <td>{{ test.approve | sumByColumn4: 'reducedTotal' }}</td>
        </tr>
      </table>
      <form>
        <div class="col-sm-4">
          <div class="form-group">
            <label for="full-name">Name</label>
            <input type="text" class="form-control" id="full-name" 
                   placeholder="Enter Full Name">
          </div>
        </div>
        <div class="col-sm-4">
          <div class="form-group">
            <label for="email-address">Email</label>
            <input type="email" class="form-control" id="email-address"
                   aria-describedby="emailHelp" placeholder="Enter email">
          </div>
        </div>
        <div class="col-sm-4">
          <button type="submit" class="btn btn-primary" style="margin-top:25px">
            Submit
          </button>
        </div>
      </form>
    </div>
  </section>

</body>        

Moreover, is it possible to update the total in column 3 of the form when the user clicks submit? Essentially, I want the sentence:

single-use plastic waste from 
<strong>
  <u>{{ test.approve | sumByColumn: 'amount' }}</u>
</strong> Items per year

to increment with each form entry by the user.

The complete code can be found here - https://codepen.io/tampham/pen/RzqLQV

In terms of calculating the difference, this is what I've attempted so far.

filter('sumByColumn5', function () {
    return function (collection, column) {
      var total = 0;

      collection.forEach(function (item) {
        total += (item.amount-item.reducedTotal);
      });

      return total;
    };
})

If you have any recommendations, I would greatly appreciate it. Thank you!

Answer №1

You have existing code to calculate the totals of column 3 and 5:

{{(test.approve | sumByColumn: 'amount') }} 
{{(test.approve | sumByColumn4: 'reducedTotal')}}

To find the difference between these two totals, you can use the following code:

{{(test.approve | sumByColumn: 'amount') - (test.approve | sumByColumn4: 'reducedTotal')}}

Check out this Demo for reference.

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

Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data. data = ['middlename.firstname.lastname','firstname.lastname']; During the process, I am looping through the .html usin ...

Trigger a function upon browsing an image in angular-bootstrap-lightbox

Currently, I am utilizing angular-bootstrap-lightbox and have the need to implement a callback function that triggers when the image is altered. In particular, for the mobile view, when a user swipes left or right, I aim to capture both the image ID and t ...

Retrieving raw PCM data from webAudio / mozAudio APIs

I have been exploring ways to store the output from the webAudio API for future reference. It seems that capturing PCM data and saving it as a file might meet my needs. I am curious to know if the webAudio or mozAudio APIs have built-in functionality for ...

The result of JWT.decode may be null

I am facing an issue with decoding a JSON web token as it is returning null. I have even tried setting complete set to true, but unfortunately it still fails. The function used for generating the token is: import jwt from 'jsonwebtoken'; jwt.s ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

Updating an element's HTML content from a template URL using AngularJS

Can someone help me figure out how to set the html of an element in my directive based on a dynamic template url? element.html('some url to a template html file'); rather than using element.html('<div>test</div>').show() ...

What is the method for inserting a new <p> tag whenever a user sends a new message in ReactJS?

Whenever I press the Enter key, the content is updated in the same tag. First I sent Hello World! The second time I tried to send Hello as a new message, it was updated within the same tag. I have shared code snippets related to the messaging function ...

Could the absence of an external style sheet for CSS be hindering the execution of my code?

A generous Stack Overflow user provided me with the code you see here and their JSFiddle can be accessed at http://jsfiddle.net/f18513hw/. The code functions properly in JSFiddle. I copied and pasted the code into my Textpad, saved it in my htdocs folder o ...

Understanding the syntax for matching files and paths in Node/JavaScript using glob, including the use of wild

I stumbled upon http://gruntjs.com/configuring-tasks#globbing-patterns and found it to be the most useful reference so far. I have come across the following statement multiple times: For more on glob pattern syntax, see the node-glob and minimatch docu ...

What are the benefits of using $locationProvider as a prefix in AngularJS?

According to the Angular documentation: While setting a prefix may not be necessary, it is generally considered a good practice (although the specific reasons are not covered in this tutorial). is often used as the default prefix. https://docs.angul ...

Steps to update the toolbar color of Mui DataGrid

Check out this unique custom Toolbar I created specifically for Mui dataGrid function CustomToolbar() { return ( <GridToolbarContainer> <GridToolbarColumnsButton /> <GridToolbarFilterButton /> <GridToolbarDensit ...

Obtaining the sum of two variables from two separate functions results in a value of NaN

Why is it that I'm seeing a NaN result when trying to access a variable in two different functions? This is my code var n_standard = 0; var n_quad = 0; var totalQuad; var totalStandard; var total = totalStandard + totalQuad; ...

Error encountered in node.js script due to misuse of Sqlite's SQLITE_MISUSE functionality

Upon running my code with this query, I have encountered a situation where all tables are listed sometimes, while other times only one table is shown and consistently the following error is displayed: Query Error: Error: SQLITE_MISUSE: unknown error I ha ...

ng-select will solely output the term 'collection'

i am having an issue with a ng-select in my contact form. everything is being received correctly except for the value of the ng-select. Instead of getting the selected option from the ng-select, the system just returns the word "array". Below is the port ...

Obtain the content of every cell in a constantly updating table

I have created a dynamic table as shown below: <table id="sort" class="table"> <thead> <tr> <th>Column Name from DB*</th> <th>Record Le ...

Use JavaScript to swap out images

How can I change the image arrow when it is clicked? Currently, I have this code snippet: http://codepen.io/anon/pen/qEMLxq. However, when the image is clicked, it changes but does not hide. <a id="Boton1" class="button" onClick="showHide()" href="j ...

Achieving Compatibility Between jQuery 3.6.0 and Node.js v12.16.1

Utilizing an online IDE known as Replit, I am working on node.js projects running on the node version: 12.16.1. However, my current challenge lies in attempting to make jQuery 3.6.0 compatible with this particular node.js version. Despite trying various me ...

What is the method to change between input sources in php?

Imagine this scenario: when a user clicks on a specific button, I want them to be presented with either a dropdown list or an input field. This decision would allow the user to choose an existing item or create a new one. <select name="choose[rowId]"&g ...

Customizing the appearance and dimensions of JWPlayer Audio Player with percentage-based styling

I'm currently attempting to set up an audio embed using JWPlayer, following the instructions provided in this particular article. The article suggests setting it up with the following code: <div id="myElement">Loading the player...</div> ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...