find total sum of elements outside ng-repeat loop

I am currently working on a calculation for the total outside of an ng-repeat, which is influenced by ng-change within the ng-repeat.

Here is a preview of my table layout:

<table>
    <tr>
        <td>Total - the total is {{tot}}</td>
    </tr>

    <tr ng-repeat="obj in Array">
         <td>
            <input ng-change="getValue(obj.Cost);" ng-model="obj.Quantity" type="number">
         </td>
        <td>
            <span ng-model="obj.ListPrice">{{obj.ListPrice}}</span>
        </td>
        <td> 
            <input type="number" ng-value="obj.Cost = obj.Quantity * obj.ListPrice">
        </td>
    </tr>
</table>

I am now in the process of calculating the overall total.

var total = 0;
$scope.getValue = function(Cost){
    total += parseInt(Cost);
    $scope.tot = total
}   

However, I'm encountering some issues with this calculation. Can you provide guidance on how to rectify this?

Answer №1

Upon initial inspection, I have identified a couple of issues in your code.

To begin with

<span ng-model="obj.ListPrice">{{obj.ListPrice}}</span>

Using ng-model on a span element is considered improper. Further information can be found in the official documentation.

Secondly

<input type="number" ng-value="obj.Cost = obj.Quantity * obj.ListPrice">

You are attempting to assign the result of obj.Quantity * obj.ListPrice to obj.Cost within the ng-value attribute. This may require further clarification for better understanding.

It seems that you may be aiming for this implementation

<input type="number" 
       ng-init="obj.Cost = obj.Quantity * obj.ListPrice" 
       ng-value="obj.Cost" />

Answer №2

It seems like your code is not functioning correctly due to the triggering of ng-change before it can calculate obj.Cost, resulting in the retrieval of the outdated value of Cost. To resolve this issue, you can implement the following approach:

$scope.getValue = function() {
  $scope.total = 0
  $scope.myArray.forEach(function(arr) {
    $scope.total += arr.Quantity * arr.ListPrice
  })
}

Incorporate the following input element:

<td>
  <input ng-change="getValue()" ng-model="obj.Quantity" type="number">
</td>

Check out the revised and functional code snippet below:

var app = angular.module('myApp', []);
app.controller("myCtrl", function($scope) {
  $scope.myArray = [{
    Quantity: "",
    ListPrice: 100
  }, {
    Quantity: "",
    ListPrice: 200
  }]

  var total = 0;
  $scope.getValue = function(obj) {
    $scope.total = 0
    $scope.myArray.forEach(function(arr) {
      $scope.total += arr.Quantity * arr.ListPrice
    })
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.js"></script>

<body ng-app="myApp">
  <div ng-controller="myCtrl">

    <table>
      <tr>
        <td>Total - total is {{total}}</td>
      </tr>

      <tr ng-repeat="obj in myArray">
        <td>
          <input ng-change="getValue(obj);" ng-model="obj.Quantity" type="number">
        </td>
        <td>
          <span ng-model="obj.ListPrice">{{obj.ListPrice}}</span>
        </td>
        <td>
          <input type="number" ng-value="obj.Cost = obj.Quantity * obj.ListPrice">
        </td>
      </tr>
    </table>
  </div>

</body>

Answer №3

To access the combined total outside of the repeating loop in AngularJS, you can follow this approach:

<span>Total is: {{total}}</span>    
<table>
    <tbody ng-init="total = 0">
    <tr ng-repeat="obj in Array">
         <td>
            <input ng-change="getValue(obj.Cost);" ng-model="obj.Quantity" type="number">
         </td>
        <td>
            <span ng-model="obj.ListPrice">{{obj.ListPrice}}</span>
        </td>
        <td ng-init="$parent.total = $parent.total + (obj.Quantity * obj.ListPrice)"> 
            <input type="number" ng-value="obj.Cost = obj.Quantity * obj.ListPrice">
        </td>
    </tr>
</table>

The ng-init inside the tbody element helps in updating the 'total' variable dynamically outside of the main loop.

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

The filter function is functioning properly when used in the console, but is not working as intended within the

I'm having some trouble filtering items using the filter method. It seems to work fine in the console, but not in the UI. I've included a couple of images to illustrate my issue. Here is an overview of what the code does: It loops through the ...

The data visualization tool Highchart is struggling to load

As I try to integrate highcharts into my website, I encounter an unexpected error stating TypeError: $(...).highcharts is not a function. Below is the code snippet in question: @scripts = {<script src="@routes.Assets.at("javascripts/tracknplan.js")" ty ...

What is the method for conducting an Ajax request?

Currently, I am deeply involved in a personal project to enhance my skills with Rails. The project involves developing a task management application that encompasses three primary states: todo, in progress, and done. After numerous days of trial and error, ...

Every time I attempt to make a "post" request to the SailsJS server, I encounter a 403 CSRF Mismatch error

Having an issue with my sailsJS server. I am attempting to send a post request from a client on a different domain. I am sending _csrf from /csrfToken, but encountering a 403 csrf mismatch repeatedly. The client-side code appears as follows: $.ajax( ...

Adjusting the minimum value on a textfield with JQuery Validate plugin in real-time

I am attempting to dynamically update the minimum value on one field based on input from other fields. Here is a brief overview of my code: $("#new_project").on("click", function() { switch($('input:radio[name=quality-level]:checked').val() ...

Ways to transfer GET form information to Express?

I am working on a form that needs to pass parameters correctly <form action="./search" method="GET"> <div class="form-group text-center"> <input type="text" name="keyword" placeholder="Search Term" /> ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

Raycasting intersections in Three.js

After successfully creating geometry and functions to manipulate it, I integrated them into a javascript UI library . However, I encountered a problem where the raycaster function was detecting intersections with geometry even when not directly under the m ...

Show the selected checkbox options upon clicking the submit button

Having trouble setting up a filter? I need to create a feature where checked values from checkboxes are displayed in a specific div after submitting. The display should include a 'Clear All' button and individual 'X' buttons to remove e ...

Better ways to conceal notifications as soon as a new one appears with Toastr

Whenever a new notification pops up in my application, I desire for the previous one to automatically disappear. It is crucial for only one notification to be displayed at any given time. Is there a way to accomplish this using toastr? ...

The error message "TypeError: scanner.js is undefined and property 'scan' cannot be read" is occurring

I've been attempting to incorporate scanner-js into my react application, but I keep encountering the error TypeError: Cannot read property 'scan' of undefined. The code snippet is provided below: import { scanner } from 'scanner-js&ap ...

A different and more efficient way to address the issue at hand

During a recent interview, I was asked the following question and despite being able to solve it, the interviewer pointed out that my code was not optimized. Is there anyone who can help me with an optimized solution? Question : Given an array array1, rea ...

When using VueJs, an error occurs when attempting to pass a dynamically generated array as a string, but there are no issues when the

I'm currently attempting to pass an array to the Draggable Vue component. The array is being generated dynamically from an inside loop, but I keep encountering the error message: Invalid prop: type check failed for prop "list". Expected Array, but rec ...

Guide on utilizing the reduce method with objects

I am attempting to use the reduce method on an object to create an HTML list const dropdownTemplate = (data) => { console.log(data); // no data displayed return ` <li class="dropdown__item" data-value="${data.value}"><span class="dropdown__i ...

Unexpectedly, Ajax call is triggering additional callbacks

I am currently facing an issue with my AJAX request in the code below. The Chrome Inspector is showing that the callback function associated with the request is being called twice, resulting in the response being logged into the console twice. Additional ...

The last javascript file that was included has been overlooked

When using jqplot, I noticed that the last included plugin is being ignored. If I switch their positions, the first to last one works while the last one does not. There are no errors in the console to indicate what might be going wrong. Moving the canvasOv ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

What steps can be taken to customize the default keyboard shortcuts functionality in Swiper.js?

I am trying to customize the functionality for left/right keys in Swiper.js but I am unable to find a way to do this through the API () It seems that the API only allows you to disable/enable default actions: mySwiper.keyboard.enabled // Whether th ...

Attempting to integrate a complex Ruby operation (using each loop and iterator) into a JavaScript platform (such as Google Charts API) by creatively combining them in a non-conventional manner during the development phase

It's time for my application to transition into production mode, and I have come to the realization that some of the code in development mode needs a major overhaul. Particularly, the views where I embedded data iteratively into Google Charts API Java ...

Seeking assistance with transmitting data to the server and retrieving it for use. I am looking to achieve this goal utilizing JavaScript with Node.js

I've been experiencing challenges with the interactions between front-end and back-end. I am confident that I am sending the data, but unfortunately, I am unable to access it afterwards. Recently, I utilized this code template (sourced from Mozilla&ap ...