What is the best way to determine a value by analyzing the items in a refined angularjs repeater?

I'm in the process of creating a scoring system and need to calculate a total score based on values from a different set of data. I came across this reference: Calculating sum of repeated elements in AngularJS ng-repeat, but I haven't been successful in making it work for my scenario as it seems to involve only one collection instead of two.

Below is the template I am working with, following the guidance provided in the aforementioned question:

<div>{{parent.id}}</div>
<div>{{ getTotal() }}</div>
<div ng-repeat="child in children | orderBy: '-postedTime' | filter: {parentId: parent.id}">
  <div>{{child.score}}</div>
</div>

The corresponding JavaScript code:

$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.children.length; i++){
    var score = $scope.child.score[i];
    total += (child.score);
}
return total;
}

Is there a way to sum up all the scores from the filtered children and display the total on the parent element?

Answer №1

If you want to calculate the sum of scores for all children belonging to a parent in AngularJS, you can utilize the "as" syntax in your filter function. This will allow you to filter the children based on their parentId and then use a custom filter called "sum" to display the total score.

Here's an example implementation:

var app = angular.module('plunker', []);

angular.module('plunker')
  .controller('MainCtrl', function($scope) {

    $scope.totalScore = 0;

    $scope.parents = [{
      id: 1
    }, {
      id: 2
    }];

    $scope.children = [{
      parentId: 1,
      score: 25
    }, {
      parentId: 1,
      score: 25
    }, {
      parentId: 1,
      score: 25
    }, {
      parentId: 2,
      score: 25
    }];
  });

app.filter('sum', function() {
  return function(kids) {
    var total = 0;
    if (kids) {
      for (i = 0; i < kids.length; i++) {
        total = total + kids[i].score;
      };
    }
    return total;
  };
});

In your HTML template, you can then use the filter along with the "sum" custom filter to display the total child scores for each parent as shown below:

<div ng-repeat="parent in parents">
  <div>Parent ID: {{parent.id}}</div>
  <div>Total Child Scores: {{ kids | sum }}</div>
  <div ng-repeat="child in children | filter: {parentId: parent.id} as kids">
    <div>Child Score: {{child.score}}</div>
  </div>
</div>

Note: The JSON data provided does not include the "postedTime" property for children, but you can easily incorporate it into your actual code as needed.

Answer №2

If you want to make things easier, consider including an ng-init to calculate the sum you require

<div ng-repeat="child in children | orderBy: '-postedTime' | filter: {parentId: parent.id}">
<td ng-init="totalScore = totalScore + child.score ">{{totalScore}</td>    
</div>

You could utilize the totalScore value wherever it is needed in your application

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

Sort an array using another array as the reference in JavaScript

I have encountered similar questions before, but my current challenge involves partially sorting an array based on values from another array. This is what I aim to achieve: let array = [ { name: "Foo", values: [a, b, c, d] }, { name: " ...

Is there a way to retrieve the filename from a callback in gulp-contains?

Currently, I am utilizing gulp-contains to scan for a specific string. If the target string is found, I intend to trigger an error message stating "String found in file abc." The 'file' parameter holds the entire object comprising filename + Buff ...

Dealing with the outcome of a synchronous AJAX request and displaying or concealing a div based on the result's value

I am attempting to run a JavaScript function that checks for internet connectivity status. If the user is connected to the internet, I do not want anything to happen on screen. However, if the connection is lost, I would like to display a div element. The ...

Simultaneous activation of two click events in Javascript

I am looking to create a game using JavaScript. The game will be designed for two players to play on the same mobile device. I am facing a challenge with coordinating the players' clicks, as they may happen simultaneously. I have attempted to use bot ...

Tips for accessing files following the transmission of a post request within the req.body

Encountering a problem where image uploads to an s3 bucket are not successful. The error message received is: API resolved without sending a response for /api/upload/uploadPhoto, this may result in stalled requests. The front end includes an input that ca ...

Clicking on the image "Nav" will load the div into the designated target and set its display to none. The div will

Can someone help me with loading a div into a target from an onclick using image navigation? I also need to hide the inactive divs, ensuring that only the 1st div is initially loaded when the page loads. I've tried searching for a solution but haven&a ...

Caution: React is unable to identify the `PaperComponent` prop on a DOM element

Trying to create a draggable modal using Material UI's 'Modal' component. I want users to be able to move the modal around by dragging it, so I decided to use 'Draggable' from react-draggable library. However, I encountered this er ...

The javascript file does not load and stringByEvaluatingJavaScriptFromString is also not running?

In my application, I am downloading an HTML file from the server and displaying it in a uiwebview. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths firstObject]; NSStri ...

Error encountered during Rocket Chat upgrade: Unable to locate migration version XXX

I have an old Rocketchat version 3.2.1 instance connected to an external MongoDB version 4.2.23. My goal is to upgrade it by connecting to a newer version of Rocketchat, specifically version 5.3.1. However, when I try to connect the new instance to the ext ...

Use the regex tag in a React component to find a specific tag by name within two different possible

Looking for a regex that can identify <Field ...name="document"> or <FieldArray ...name="document"> within a multiline text string so they can be replaced with an empty string. The text string is not formatted as HTML or XHTML, it simply conta ...

A regular expression in Javascript that can be used to identify at least one word starting with a number among multiple words, with a

Currently, I am utilizing JavaScript Regex to validate an input field based on specific conditions: The value must consist of only alphabets and numbers There should be a minimum of two words (more than two are allowed) Only one word can start with a num ...

Assigning controller variables within an ajax request

I'm new to AngularJS and I have a question about controller attributes. I've created an attribute called 'anuncio', which contains an array of objects as shown below: var anuncioModule = angular.module('anuncioModule',[]); a ...

Ionic side menu failing to update its content

Hello, I am facing an issue with my Ionic side menu. It contains sign-up and sign-in links that I want to hide based on the logged-in state. When a user is logged in, the sign-in and sign-up links should be hidden. If not logged in, both links should be v ...

I'm encountering a problem with my vuejs application

I am currently working on a new vuejs 2 app and encountered an unexpected error. ERROR in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0&bustCache!./src/components/Customers.vue Module build failed: S ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

Troubleshooting issue with Mongo aggregation and $lookup when utilizing let clause

There are documents in collectionA like this: { "catalogId" : "17582" } And in collectionB, documents look like this: { "product" : { "catalogId" : "17582" } An aggregation is being applied to collectionA: { $lookup: { from: ...

Create a global variable by importing an external module in TypeScript

I am currently developing a TypeScript npm module called https://www.npmjs.com/package/html2commonmark. This module is versatile and can be utilized in nodejs (via require) as well as in the browser (by loading node_modules/html2commonmark/dist/client/bund ...

Reactjs implemented with Material UI and redux form framework, featuring a password toggle functionality without relying on hooks

Currently, I am working on a react project where I have developed a form framework that wraps Material-UI around Redux Form. If you want to check out the sandbox for this project, you can find it here: https://codesandbox.io/s/romantic-pasteur-nmw92 For ...

The bidirectional linking of a model within a directive is not functioning

After receiving feedback on one of my previous questions, I decided to experiment with creating a directive in order to streamline my code. Here is what I came up with: Directive (initially small for testing purposes, will be expanded later): BebuApp.dir ...

Sorting dates in Mongoose's aggregation feature is not functioning properly

Could someone please explain why the results of this aggregation query are not being sorted by the created_at date? User.aggregate([ // Filtering for records created within the last 30 days { $match: { "created_at":{ $gt: new Date(today.getTime() - ...