A method for calculating the total value of a particular attribute within an ng-repeat loop

I am trying to develop a function that can calculate the total value of a specific property retrieved from a JSON web service.

Here is my function:

$scope.exportData = data;

$scope.totalLW = function() {
    $scope.total=0;

    for (var i = 0; i < $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW.length; i++) {
        $scope.total += parseFloat($scope.exportData.result.merchMetrics.SALES_AMOUNT_LW);
    }

    return $scope.total;
}

I am calling this function in my HTML view like this:

<td ng-class = "{'positive':totalLW() >= 0, 'negative': totalLW()}">{{totalLW()}}</td>

However, I am encountering an undefined error in my view. I suspect there might be an issue with my function implementation and need assistance in identifying the problem.

The variable $scope.exportData seems to be functioning properly as the table binding is working correctly.

Attached below is a screenshot:

https://i.sstatic.net/KMIED.png

Answer №1

It appears that you overlooked using array values in a for loop.

 $scope.totalLW = function (){
          $scope.total=0;
          for(var i =0; i < $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW.length; i++ ) {

         $scope.total += parseFloat($scope.exportData.result.merchMetrics.SALES_AMOUNT_LW**[i]**);
       }
       return $scope.total;
    }

After further investigation, I discovered the point that was missed. You should iterate through

for (var i =0; i <$scope.exportData.result.length; i++)
on $scope.exportData.result not on $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW

Answer №2

Before the data is available, the view will execute that function.

This means that you may try to access properties of an object that does not yet exist during the initial view setup, resulting in errors.

An alternative approach could be to simply wait for the data instead of using a function within the view.

Once the data is received, you can utilize Array.prototype.reduce() to calculate the total:

$scope.total =  data.result.merchMetrics.SALES_AMOUNT_LW.reduce(function(total, curr){
   total += (parseFloat(curr.SALES_AMOUNT_LW) || 0); 
   return total;
},0)

View

<td ng-class = "{'positive':total, 'negative': total < 0}">{{total || 0}}</td>

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

Unsyncing your GIFs

I'm struggling to asynchronize these two GIF images. I've tested them on Opera and Edge browsers. My expectation was for the second GIF to start its animation independently when I begin the first one (on the left). Unfortunately, they are not d ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...

Implementing dynamic controls in an ASP.NET MVC5 application using AngularJS

I am currently working on a project that will utilize MVC5, angularJS, and bootstrap for development. One of the key features in my project is a dropdown menu called "expense type". Upon selecting a value from this dropdown, additional controls need to be ...

Troubleshooting: Issues with AngularJS Data Binding in HTML Tables

I have been working on code from an online tutorial but unfortunately, it is not functioning properly. I have checked the script, app, and controller but still cannot identify the issue. Any assistance would be greatly appreciated! ...

The inline variables in CSS transitions are failing to be detected

The CSS transitions are not recognizing the inline variables, or if they are, they are not receiving the correct information. Below is an illustration of how the inline variables are defined in the HTML: <p class="hidden" style="--order ...

Create a fresh array by merging two existing arrays together

My project involves working with two separate arrays. The first array contains normal date values: var = [ "2022-05-01", "2022-05-02", ... "2022-05-30" ] The second array consists of objects that contain s ...

Removing elements from an array based on a specified condition

I am having trouble deleting JSON elements that meet a certain condition. I tried using the following code: var index = -1; for (var i = 0; i < data.dashLayout.dashlets.length; i++) { if (data.dashLayout.dashlets[i].rowNo == selectedrowno) { if ( ...

Increase the value of count (an AJAX variable) by 4 upon clicking the button, then send it over to the PHP script

I'm facing an issue where my AJAX variable is only updating once by +4 each time a button is pressed. I need assistance on how to make it continuously work. index.php - AJAX <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.m ...

What is the most effective method for storing multiple data points in an array?

I have developed the following script: let data = [ {day: 1, time: '08:00', note: 'madrid'}, {day: 2, time: '08:00', note: 'barcelona'}, {day: 3, time: '10:00', note: 'juve ...

AdminLTE-3 Bootstrap-4 sidebar menu with dynamic AJAX functionality fails to toggle treeview open/hide after page is fully loaded

I am looking to update the sidebar menu dynamically in the adminlte 3 dashboard with bootstrap 4 using AJAX calls. However, I have run into an issue where the menu open/close functionality is not working when the data is loaded dynamically using AJAX. On t ...

Utilizing jQuery to dynamically convert a dropdown into a multiselect when triggered by the selection of another dropdown within a form containing cloned

After coming across discussions on using a multiselect based on another multiselect, cloning a form row, and dynamically updating select options, it seems there are no answers detailing how to combine all three concepts together. In my particular scenario ...

Recognize when the DOM undergoes modifications

After taking Matt's suggestion, I have made changes to the .ready() call. In my workflow, I utilize jQuery to set up certain configurations like this: $(function () { $('.myThing').each(function() { ... configuring happens he ...

Adjusting the height of a vertical slider in Vuetify2 is not customizable

I've been trying to adjust the height of a vertical slider in vuetify2, but setting it to "800px" or using style="height:800px" doesn't seem to work as intended. Even though the box within my grid expands, the height of the slider remains unchan ...

Is there a correct way to properly duplicate a JSON array in Redux?

As a newcomer to Redux, I found the concepts somewhat confusing at first. For instance, imagine that there is an array in the redux state. const state = [ {show: false, id : '1'}, {show: false, id : '2'}, {show: false, id : &apo ...

React Native Navigation Issue: The route's component must be a valid React Component

Hello everyone, I am a beginner in the world of React Native and I am currently working on creating a simple navigation system. However, I have encountered an error that I am unable to resolve. Can anyone provide me with some guidance? Click here for the ...

Ways to select a random row from a MySQL database

<button onclick="myUniqueFunction()">Press here!</button> <?php function myUniqueFunction() { $con = mysqli_connect("mysql.hostinger.no", "u452849516_altge", "password", "u452849516_altge"); $query = "S ...

How can a web developer prevent image caching in HTML5 for optimal performance?

Currently, I am facing an issue with my application where it keeps overwriting the image in localhost every 40 milliseconds. To display this constantly changing image (with the same name) in an HTML5 image tag, I am trying to load it also every 40 millisec ...

Jquery and Magento Prototype causing conflicts

I am attempting to implement the Foundation 5 Reveal modal on a Magento product page. To do this, I have included jQuery and foundation.js in the footer and initialized Foundation from footer.phtml <script src="js/vendor/jquery.js"></script> ...

Is there a way to accurately determine the width of a DOM element in a ReactJS application?

While working on a web application using reactjs, I encountered an issue with creating a video player within a specific div container. To address this, I implemented the functionality in the 'componentDidMount' function as shown below: componen ...

Steps for writing code to append and execute code snippets using values from a JSON dataset

My attempt to fetch the result through this code is I am looking to display 'Y' or 'N' in the columns Mon, Tue, Wed, Thu, Fri, Sat, Sun I am facing issues fetching the 'run' value from the json data. I have used user.days to ...