Combining the elements of a nested array using AngularJS within a loop

I attempted to showcase the values of AngularJS. Now I aim to aggregate all these values into its parent variable sum.

This is How my AngularJs Array Appears:

{  
   "isInternalInvoice":1,
   "name":"Invoices",
   "sum":50,
   "articles":[  
      {  
         "ID":"130.0000917-17.557000506.1",
         "betrag_netto":"20",
      },
      {  
         "ID":"130.0000917-17.557000581.1",
         "betrag_netto":"30"
      }
   ]
}

Snippet of Code:

<tr ng-repeat="invoice in currentInternalInvoices" >

 <input type="text" ng-model="invoice.betrag_netto"  />

</tr>

By making amendments in the textbox, it successfully updates the sum:

<input type="text" ng-model="$parent.data.sum" ng-bind="$parent.data.sum"  />

However, I wish to automatically add up all values as I type within the loop.

Answer №1

Simply create a function that calculates the sum

$scope.calculateSum = function() {
  return $scope.data.articles.reduce((a, b) => a+Number(b.betrag_netto), 0);
}

Add an element to display the sum

<div>{{calculateSum()}}</div>

The value will update automatically whenever there are changes in the input boxes.

Check out this example on Plunker

Answer №2

To enhance the functionality, update the HTML by including an ng-change event listener that calculates the sum as the input field is modified.

<tr ng-repeat="invoice in currentInternalInvoices" >

 <input type="text" ng-model="invoice.betrag_netto" ng-change="calculateTotal()" />
</tr>
<input type="text" ng-model="data.totalAmount"   />

Implement this code in the controller to manage the summation process:

$scope.calculateTotal = function() {
    $scope.data.totalAmount = $scope.data.items.reduce((a, b) => a + Number(b.betrag_netto), 0);
}

Answer №3

To implement a unique solution, consider developing a personalized directive

(function() {
  "use strict";
  class CustomDirectiveController {
    constructor(dataService) {
      this.dataService = dataService;
      this.data = {
        total: 0
      }
    }
    $onInit() {
      this.data = this.dataService.fetch();

      console.info('executing');
    }

    static get $inject() {
      return ['dataService'];
    }

  }

  const customApp = angular.module('customApp', [])
    .service({
      dataService
    })
    .controller({
      CustomDirectiveController
    })
    .directive({
      calculateTotal
    });


  function calculateTotal() {
    return {
      restrict: 'A',
      bindToController: {
        total: '=',
        source: '=',
        by: '@',
      },
      scope: true,
      controller: class {

        $doCheck() {
          this.total = this.source.reduce((sum, {
            [this.by]: value
          }) => Number(sum) + Number(value), 0);
        }
      }
    }
  }

  function dataService() {
    return {
      fetch() {
        return {
          "isInternalInvoice": 1,
          "name": "Invoices",
          "total": 50,
          "items": [{
              "ID": "130.0000917-17.557000506.1",
              "net_amount": "20",
            },
            {
              "ID": "130.0000917-17.557000581.1",
              "net_amount": "30"
            }
          ]
        };
      }
    };
  }

}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<div ng-app="customApp" ng-controller="CustomDirectiveController as ctrl">
  <table total="ctrl.data.total" by="net_amount" source="ctrl.data.items">
    <tr ng-repeat="item in ctrl.data.items">
      <td>
        <input type="text" ng-model="item.net_amount">
      </td>
    </tr>

  </table>
  {{ctrl.data | json}}
  <div></div>
</div>

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

Navigating to the end of a webpage using Vuetify

I am looking to create an application that consists of multiple card views and a button that scrolls the page to the bottom upon each click. While I have come across solutions using native JavaScript for scrolling, I am unsure how to implement this functi ...

Combine table cells to improve readability on smaller screens

I currently have a setup designed for larger screens: <table> <thead> <tr> <th>title and image</th> <th>description</th> </tr> </thead> <tbody> ...

Issues with Ajax Requests

The pending requests from the Post need to be completed. I was hoping to record the JSON body of the request that comes in. Everything works fine when using Postman, but for some reason the AJAX requests are not functioning properly. Code snippet for Node ...

Angular's parent div height can be adjusted using CSS transitions

I have implemented a CSS transition to create a sliding effect in my pagination. However, I am facing an issue where the height of the containing div changes even when I set the position of the transitioned elements. Here is a snippet of my CSS: .slide { ...

Background image fixed with scrolling effect

I've been struggling with a parallax effect on my website. After seeing it work smoothly on other websites, I tried to implement it myself but couldn't quite get it right. The background image keeps moving when I scroll the page and I want it to ...

Launching an external JavaScript from within a separate JavaScript file

I'm in the process of developing a virtual 'directory' for various locations in my city to assist fellow students. Here's the concept: On a map, I've pinned all the locations Clicking on these pins triggers a JavaScript funct ...

Displaying outcomes solely based on JSON upon choosing a filter

Goal I aim to only show results once their respective state is chosen. Currently, all results are displayed automatically upon page load. I prefer if nothing is shown initially. Only when a state is selected should the corresponding results appear. Bac ...

Negative values cannot be used as the starting point for a for loop

For this project, I am tasked with creating an array that can be referenced from the range of -2 to 25. Everything runs smoothly if the starting point is at 0, but for a low pass filter implementation, I also require the values of x(n) at positions -2 and ...

Is there a way to automatically refresh a webpage in HTML that encounters an error?

I am facing a strange issue. There is a php script that runs exclusively on our webserver, processing a large amount of data immediately after a new job is added to the database. The processing typically takes around 1-5 minutes. To monitor for unfinished ...

regex tips for updating URLs within CSS using JavaScript

var content = '$content {style:url("csshover.htc");}'; //using " with link content += "$content {background:transparent image('pic.png') no-repeat;}"; //using ' with web address content += "$content {bg-image:url('awesome.jpg& ...

Tips for utilizing the useState Hook in NextJs to manage several dropdown menus efficiently:

Currently, I am in the process of designing an admin panel that includes a sidebar menu. I have successfully implemented a dropdown menu using the useState hook, but it is not functioning exactly as I had envisioned. My goal is to have the if statement onl ...

What is the purpose of the code snippet 'jQuery.each(lines, function(lineNo, line)'?

As a newbie to jquery and ajax, I stumbled upon some code online that caught my attention. The code snippet below prompted me to question its purpose and functionality: lines = newLine.split('#'); jQuery.each(lines, function(lineNo, line) ...

Accessing this.href from the ASP.NET code behind using Javascript

I'm trying to pass this.href from my asp.net code behind to JavaScript. When I run the code, the value appears as 'undefined' in the alert message. Can anyone help me with this issue? Page.ClientScript.RegisterStartupScript(this.GetType(), ...

Leveraging Promises within if conditions

Has anyone encountered difficulties using Promises within an if condition? I'm currently dealing with a problem where the code continues to execute even when the if statement is false. Any suggestions on how to resolve this issue? For a detailed exam ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Attempting to alter the background image through the action of clicking on an image using jQuery, HTML, and CSS

I have created custom weather icons like a sun, cloud, and rainy cloud using Photoshop. My goal is to allow users to click on these icons and change the background image of the website's body. However, despite my efforts, clicking on the images does n ...

Omit specific module from a webpack 4 chunk

Is there a way to exclude a specific module from being included in a chunk using webpack 4? For example, let's say I do not want lodash to be included in the vendor file at all costs. How can this be achieved? Here is the current configuration: spli ...

Reordering div elements with JavaScript

Let's say we have the following structure: <div id="left"> <div id="1"></div> <div id="2"></div> <div id="3"></div> <div id="4"></div> <div ...

What could be the reason for the page scrolling upwards when clicking on href="#"?

I am encountering an issue with a hyperlink <a href="#" id="someID">Link</a> that is located further down the page. This link is used to trigger an Ajax request, but whenever it is clicked, the page automatically scrolls back to the top. I have ...

Freemarker substitute & and &ampersand;

I am facing an issue with Freemarker. I need to eliminate all the special characters from this sentence as well as from similar sentences in the future: BLA BLA RANDOM &, RANDOM BLA In particular, I want to remove the & character. The platform ...