Combining values in AngularJS and summing them up within ng-repeat

Currently, I am working on calculating the total sum of a group in AngularJS. My approach involves using http to retrieve results and display them in an HTML table:

$http({method: 'GET', url: urlpurchasing}).success(function(data) {
    $scope.purchasing = data;
})

As shown in the link below:

I aim to create a new column named "total stock" where the "Quantity sold" for each group will be added up. Specifically, I want to aggregate the "quantity sold" values for groups that share the same description. For instance, the three purple rows at the end should have a total of "607" in their respective "total sold" column.

I attempted to iterate through the data using an angular foreach loop and keep track of the cumulative total. However, this method requires creating a secondary array which can lead to discrepancies when filtering or altering the main table. Any help on this issue would be much appreciated.

Edit:

Below is my current solution, wherein the totals are repeatedly increasing:

$http({method: 'GET', url: urlpurchasing}).success(function(data) {
    var t = 0;
    
    angular.forEach(data, function(obj){
        if($scope.code == obj.GroupCode){
            
        } else {
            $scope.code = obj.GroupCode;
            t = 0;
        }
        
        t = (t + parseInt(obj.QuantitySold));
        obj.total = t;
    });
    
    $scope.purchasing = data;
})

This PHP script retrieves data from the database:

<?php

require_once('sqlconnect.php');
$sqlQuery = "select StockCode, Description, QuantityInStock, QuantitySold, NetAmountSold, GroupCode, color from purchasing order by Description desc"; 
$result = $unity_connection->query($sqlQuery);

$json1 = array();
while ($rows = mysqli_fetch_assoc($result)) {
    $json1[] = $rows;
}   

echo json_encode($json1);

?>

Answer №1

Although I am not a user of MySQL, utilizing standard SQL should prove to be effective in this scenario:

SELECT
    items.product_code,
    items.description,
    items.stock_quantity,
    items.quantity_sold,
    items.net_amount_sold,
    items.category,
    items.color,
    summary.total_stock
FROM
    items join (select description, sum(quantity_sold) as TotalStock from items group by descrption) summary on items.description = summary.description 
ORDER BY items.description DESC

Answer №2

To achieve this, you have a few options. You can create an additional variable for the total in your controller scope, add it directly to your data JSON file, or extend the $scope.purchansing object.

Alternatively, if you prefer not to add any more properties to $scope, you can calculate the total for each group at runtime by calling a function.

Check out this example where I used a runtime function to calculate the group totals.

Update: Here is an updated example showing how to extend your scope data in the controller.

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

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

"Clicking on AppBar MenuItem functions properly on desktop, but it does not work on mobile devices in Material UI using

Within my reactjs application that employs Material UI, I have a Appbar containing a dropdown menu positioned in the top right corner. On desktop, the onClick function for each MenuItem works as expected. However, on mobile devices, the function does not t ...

Preloading error alert message displayed during AJAX request

When I send an ajax request with a dropdown change, the loader div is shown using "before send". However, the issue is that the loader only displays for the first time, even though the ajax functionality works all the time. If you want to check this issue ...

An issue has been detected in the constants.json file located in the constants-browserify

I organized my folders into client-side and server-side categories, but I failed to work from a parent folder perspective. Now, as I attempt to deploy to Heroku, I realize that I need one main folder for the deployment process. To address this issue, I dec ...

Discrepancy in Metalness Between GLTF Scene and THREE.JS Editor's Environment Available at https://threejs.org/editor/

I have encountered an issue with a gltf file. When I import it into the Three.js editor (), everything appears as expected when adding an environment map. However, when I import the same gltf file into my project scene, I notice a discrepancy in the resul ...

Is it possible to combine useEffect with asynchronous functions?

Here is the code snippet in question: useFocusEffect( useCallback(async () => { const user = JSON.parse(await AsyncStorage.getItem("user")); if (user.uid) { const dbRef = ref(dbDatabase, "/activity/" + user.uid); ...

What is the best method for inserting a 'Placeholder' in an Angular datePicker?

Looking for assistance with placing placeholder text inside an Angular datePicker, specifically wanting to display 'From' and 'To' labels within the datePicker. datePicker I am a novice when it comes to Angular development - can someon ...

Vue.js 2: Sorting ul list based on user input text

Is there a way to filter a list dynamically based on either the name or initials that a user types into an input field? I am currently utilizing vue.js 2 for this task. The list is populated by accessing a store variable which stores data from a JSON file. ...

Is it possible to validate the data first before returning a resolve?

How can we use a Promise to resolve if all fields are valid or reject if any field is invalid? let validateData = (data) => { let fields = [ 'Field1', 'Field2', 'Field3' ]; return new P ...

Fullpage.js paired with a carousel

Is there a reason why two carousels are not aligning side by side when using fullpage.js? It seems to work perfectly fine without fullpage.js! In Fullpage.js, even after separating the columns for the two carousels, they end up overlapping each other. How ...

Is it possible to modify the default behavior of a sensitive region within a button?

I created a calculator application in React and overall, it's working fine, however... I've noticed that when I hold a click longer, it only registers as a click if the mouse was pressed down and released on the button itself. Although I unders ...

Is there a way to prevent mouse hover propagation in React.js, similar to how we can do with onMouseEnter

When using onMouseEnter on a parent div and mouse hovering over a child element, the parent's mouseHover event is triggered. Despite trying to stop it with e.stopPropagation(), the parent's mouseHover event still fires. Is there a way to prevent ...

reviewing the content of an element upon mouse hover

I'm having trouble setting up a mouse enter event that should trigger if the element contains specific text. However, for some reason, it seems like the :contains parameter is not being recognized. Here is the HTML: <div class="sample">red< ...

Developing a fresh entity in the world of three.js

Currently engaged in a project that involves creating 3D objects using Three.js, sourced from databases. The connection is established, but encountering failures when attempting to generate a new object. this.type = 'CustomObject'; let shape = ...

Struggling to remove an image while using the onmouseover event with a button?

I am encountering an issue with hiding an image using the onmouseover event not applied directly to it, but rather to a button element. The desired functionality is for the image to appear when the mouse hovers over and disappear when it moves away. Here&a ...

Tips for sending an array of inputs to the query selector in Node.js using Cloudant

Currently, I am attempting to retrieve documents from a cloudant database using node.js. While I have successfully managed to obtain results for a single input value, I am encountering difficulty when it comes to querying with an array of inputs. For a si ...

Issue with Achieving Two-Way Binding in Angular 1.5 Component when using $ctrl

I am struggling with customizing some products using a component in my index.html. Ultimately, I need to calculate the total of selected products within the main controller "planosVoz" using two-way binding on the svaTotal property in the component control ...

Unable to show the list of comments with jQuery functionality

Having trouble with my code to display the comment list correctly. I can't seem to get the expected result, could you please review it and help me find the mistake. The current output is as follows: var item = $('<div>'); $.each(d ...

How to retrieve the ID of the inserted record in Knex.js

I was trying to add a new note to the quoteNotes table. However, after inserting it and logging the response, I noticed that there was no record of the inserted note showing up. router.post('/:id/notes', (req, res) => { const {id} = req.para ...

How come Axios is still logging error 403 even after I try to catch it?

After reviewing the axios documentation, I placed the catch block following my request. However, despite catching and displaying the error in an Alert, the browser console still shows the message: POST http://localhost:5000 403 (Forbidden) spread.js: ...