What is the formula for finding the total of rows when using ng-repeat?

I have a unique requirement that I would like you to consider before labeling as a duplicate. Let's delve into the following example:

<table ng:init="stuff={items:[{description:'gadget', cost:99,date:'jan3'},{description:'thing', cost:101,date:'july6'},{description:'thing', cost:101,date:'jan3'} ]}">
    <tr>
        <th>Description</th>
        <th>Cost</th>
    </tr>

    <tr ng:repeat="item in stuff.items|filter">   /*only display filtered items grouped by date*/    
        <td>{{item.description}}</td>
        <td ng-bind='item.cost'>{{item.cost}}</td>
    </tr>

    <tr>
        <td></td>
        <td>{{total}}</td>   /*total cost of items grouped by date jan3*/
    </tr>
</table>

How can I calculate the total cost of grouped items? Is there a data attribute in Angular where I can store and sum up the costs for each grouped item, before moving on to the next group?

Answer №1

Angular version 1.3 introduced a feature that allows you to create an alias for your ng-repeat, particularly beneficial when combined with a filter.

variable in expression as alias_expression
– In addition to the main expression, you can specify an optional alias expression to hold the results of the repeater after applying filters. This is commonly used to display a special message if a filter is active on the repeater but produces an empty result set.

For instance:

item in items | filter:x as results
assigns the filtered items fragment to results, but only after filtering.

Therefore, you can leverage as alias_expression for performing calculations on the filtered subset of your list. For example:

<tr ng-repeat="item in stuff.items|filter as filteredStuff">
  {{filteredStuff.length}}
  {{calculateTotal(filteredStuff)}}
</tr>

In the controller:

$scope.calculateTotal = function(filteredArray){
    var total = 0;
    angular.forEach(filteredArray, function(item){
        total += item.cost;
    });
    return total;
};

Answer №2

If you want to calculate the total cost of all items in an array, you can create a custom filter for that purpose.

Custom Filter Markup

<tr ng:repeat="item in filteredData = (stuff.items|filter)">
    <td>{{item.description}}</td>
    <td ng-bind='item.cost'>{{item.cost}}</td>
</tr>
<tr>
    <td></td>
    <td>{{filteredData| total}}</td>   /*Total cost of grouped items*/
</tr>

Custom Filter Code

app.filter('total', function(){
  return function(array){
    var total = 0;
    angular.forEach(array, function(value, index){
       if(!isNaN(value.cost))
        total = total + parseFloat(value.cost);
    })
    return total;
  }
})

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

Is it possible to retrieve or modify the dimensions and position of an element set in a static position using only JavaScript?

Is it possible to access or modify the coordinates, width, and height of an element that is statically positioned using only JavaScript? If so, how can this be done in both pure JavaScript and jQuery? ...

What is the process for setting data in a subgrid within an expandable grid?

Here is the structure of my array: $scope.ebObjArr = [{key: 'val', monthsArray: [{myDate:'',}]},{myDate:'',}] The monthsArray is responsible for populating the sub-grid. I am struggling to figure out how to populate data in ...

What is the solution for addressing the absence of an 'Access-Control-Allow-Origin' header in the requested resource while using axios?

Here is my Vue script: <script> export default { ... methods : { login() { // uri -> http://my-app.test/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472b28202e2978222a262e2b7a332234330720 ...

What could be causing the sorting function to malfunction on certain columns?

My table's column sorting feature works well with first name and last name, but it seems to have issues with dl and dl score columns. I need assistance in fixing this problem. To access the code, click here: https://stackblitz.com/edit/angular-ivy-87 ...

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

Developing novel errors in JavaScript

There are times when I overlook using the await keyword, for example: const foo = bar(); // as opposed to const foo = await bar(); Identifying these bugs can be challenging. Are there any methods, libraries, or tools that can help prevent such errors? ...

How can I send a Vue.js object to a Laravel controller?

I am working with a Vue component that includes an object like this - dataObj = [{id:1,name:'sanaulla'},{id:1,name:'parvez'}] When I try to send a post request to the Laravel Controller using the following code - axios.post("/api/ ...

The Jquery .clone() function presents issues in Internet Explorer and Chrome browsers, failing to perform as expected

I need to duplicate an HTML control and then add it to another control. Here is the code I have written: ko.bindingHandlers.multiFileUpload = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { va ...

Tips for displaying text within an input field labeled "password" and then reverting back to a password display after entering text

I am working with a login form that includes a password field: <input type="password" name="password" id="password" value="Password" maxlength="40" required style="width: 130px; font-size: 10px;" /> Currently, the password field displays "******** ...

The functionality of animation is disrupted by jQuery-ui

I am facing an issue with a div that contains some animation. When I include jquery-ui, the animation event does not trigger. Interestingly, if I disable the jQuery-UI lines, everything functions properly (except for the UI features). Below is a snippet of ...

CSS code for vertical navigation arrows to remain on both the left and right sides of the webpage

I'm struggling a bit with the CSS. I want to recreate the same effect as seen on . The left and right navigation arrows stay fixed vertically even when scrolling up or down the page. Does anyone have any code examples for that? ...

What is the best way to link options from a select directive with a different array?

Update: the working jsfiddle can be found here: http://jsfiddle.net/robertyoung/jwTU2/9/ I'm in the process of developing a webpage/app using AngularJS. The specific functionality I aim to achieve involves allowing users to add a row to the timecard ...

Issue Detected at a Precise Line Number - Android Studio

Despite my numerous attempts to modify the specific line in question, including leaving it empty, turning it into a comment, or removing it entirely, the error message persists. I even went as far as deleting the class and creating a new one, but the same ...

Is there a way to detect any changes within a div element?

Similar Question: How to Detect Changes in Element Content Using jQuery In one of my divs, I have various text fields, radio buttons, and text areas. I want to determine if there has been any change in the content within this div. For example... < ...

Encountering an issue while trying to import express from the express module

Currently working on a MERN app and encountering an error while trying to import express. The specific error message I am receiving is SyntaxError: Cannot use import statement outside a module. Here's a snippet of my code: import express from 'ex ...

Is there a way to prevent Angular component lifecycle hooks like ngOnInit/ngOnDestroy from being triggered when nested within one another?

I am currently developing an application with a page structure that resembles the following: Displaying Objects retrieved from Firestore (similar to Instagram posts) Loading Comments (using the object's id to display comments sub-collection) Load ...

Exploring AngularJS's capabilities with asynchronous tasks

I am in the process of developing a simple app using AngularJS. One of the key functionalities I am working on is removing items from a list. To achieve this, I have created the following code snippet: $scope.removeItem = function(item) { var toRemove = ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Transform the JavaScript function to a Node.js module

My function serves as an abstract factory for creating JavaScript objects. Here is the code: var $class = function(definition) { var constructor = definition.constructor; var parent = definition.Extends; if (parent) { var F = function ...

The Vuex state item is consistently found to be void of any content

After integrating Vuex into my project, I have encountered a peculiar issue. Within the filters module, the structure is as follows: import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default { namespaced: true ...