Determine the dynamic total value using AngularJS

My JSON object contains a list of products

[
  {
    "id": 22565423428,
    "title": "SV 8GB USB Flash Memory E100",
    "imageUrl": "/images/22565423428.png",
    "url": "/products/22565423428",
    "prices": [
      {
        "amount": 159.92,
        "currency": "SEK"
      }
    ]
  },
  {
    "id": 22565423394,
    "title": "Litware Wireless Mouse M35",
    "imageUrl": "/images/22565423394.png",
    "url": "/products/22565423394",
    "prices": [
      {
        "amount": 239.6,
        "currency": "SEK"
      }
    ]
  }
]

Below is my ng-repeat code for iterating through the products

<ul>
<li class="basket-item" ng-repeat="product in products">
  <div class="product-item-image">
     <img src={{product.imageUrl}} />
  </div>
  <div class="product-item-description">
      <h2><a href="product.html">{{product.title}}</a></h2>
      <a href="#">Description</a>
  </div>
  <div class="product-item-qtn">
      <input type="number" name=quantity ng-model="quantity" ng-init="quantity = 0"> st
      <p><b>quantiy</b>1-3</p>
  </div>
  <p class="product-item-price">x {{product.prices[0].amount}} {{product.prices[0].currency}}</p>
  <p class="product-item-total" >{{product.prices[0].amount * quantity}}</p>
  </li>
 </ul>

The total amount changes when users modify the quantity.

I am looking for a way to dynamically calculate and display the total amount across all products

 <span>{{totalAmount}}</span>

Answer №1

I created an example quickly based on the code you shared.

Just a couple of things to note:

  1. Ensure to use product.quantity instead of just quantity.

  2. Refer to the controller function calcTotal() for calculating the total.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Products</title>
    <!-- AngularJS -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="MyCtrl">

    <ul>
        <li class="basket-item" ng-repeat="product in products">
            <div class="product-item-image">
                <img src={{product.imageUrl}} />
            </div>
            <div class="product-item-description">
                <h2><a href="product.html">{{product.title}}</a></h2>
                <a href="#">Description</a>
            </div>
            <div class="product-item-qtn">
                <input type="number" name=quantity ng-model="product.quantity" ng-init="product.quantity = 0"> st
                <p><b>quantiy</b>1-3</p>
            </div>
            <p class="product-item-price">x {{product.prices[0].amount}} {{product.prices[0].currency}}</p>
            <p class="product-item-total" >{{product.prices[0].amount * product.quantity}}</p>
        </li>
    </ul>

    <h1>Total: {{calcTotal()}}</h1>

</div>

<script>
    var app = angular.module('myApp',[]);

    app.controller('MyCtrl', ['$scope', function($scope) {
        $scope.products= [
            {
                "id": 22565423428,
                "title": "SV 8GB USB Flash Memory E100",
                "imageUrl": "/images/22565423428.png",
                "url": "/products/22565423428",
                "prices": [
                    {
                        "amount": 159.92,
                        "currency": "SEK"
                    }
                ]
            },
            {
                "id": 22565423394,
                "title": "Litware Wireless Mouse M35",
                "imageUrl": "/images/22565423394.png",
                "url": "/products/22565423394",
                "prices": [
                    {
                        "amount": 239.6,
                        "currency": "SEK"
                    }
                ]
            }
        ];

        $scope.calcTotal= function(){
            $scope.total = $scope.products.reduce(function(totalCost, product) {
                return totalCost + product.quantity*product.prices[0].amount;
            }, 0);
            return $scope.total;
        }
    }]);

</script>
</body>
</html>

Answer №2

Create a new function in your controller called totalPrices() to calculate the total price of all products, taking into account the quantity of each item. Make sure that each product has a quantity property so it can be used when calculating the total. The function should look like this:

  $scope.totalPrices = function(){
    var sum = 0;
    angular.forEach($scope.products, function(product){
      sum += product.prices[0].amount * product.quantity;
    });
    return sum;
  } 

Keep in mind that if you add more items to the prices array, you will need another nested loop for each item. Below is the updated HTML with an additional controller and changes to how quantity is handled:

  <body ng-app="app">
    <div ng-controller="ctrl">
      <ul>
       <li class="basket-item" ng-repeat="product in products">
        <div class="product-item-description">
            <h2><a href="product.html">{{product.title}}</a></h2>
            <a href="#">Description</a>
        </div>
        <div class="product-item-qtn">
            <input type="number" name=quantity ng-model="product.quantity"> st
            <p><b>quantiy</b>1-3</p>
        </div>
        <p class="product-item-price">x {{product.prices[0].amount}} {{product.prices[0].currency}}</p>
        <p class="product-item-total" >{{product.prices[0].amount * product.quantity}}</p>
        </li>
        <p>{{totalPrices()}}</p>
       </ul>      
    </div>
  </body>

Check out a Plunker Example here

Answer №3

You have the option to implement a solution like this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Products</title>
    <!-- AngularJS -->
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
</head>
<body ng-app="myApp">

<div ng-controller="MyCtrl">

    <ul>
        <li class="basket-item" ng-repeat="product in products">
            <div class="product-item-image">
                <img src={{product.imageUrl}} />
            </div>
            <div class="product-item-description">
                <h2><a href="product.html">{{product.title}}</a></h2>
                <a href="#">Description</a>
            </div>
            <div class="product-item-qtn">
                <input type="number" name=quantity ng-model="product.quantity" ng-init="product.quantity = 0"> st
                <p><b>quantiy</b>1-3</p>
            </div>
            <p class="product-item-price">x {{product.prices[0].amount}} {{product.prices[0].currency}}</p>
            <p class="product-item-total" >{{total[$index]=product.prices[0].amount * product.quantity}}</p>
        </li>
    </ul>

    <h1>Total: {{getTotal()}}</h1>

</div>

<script>
    var app = angular.module('myApp',[]);

    app.controller('MyCtrl', ['$scope', function($scope) {
        $scope.products= [
            {
                "id": 22565423428,
                "title": "SV 8GB USB Flash Memory E100",
                "imageUrl": "/images/22565423428.png",
                "url": "/products/22565423428",
                "prices": [
                    {
                        "amount": 159.92,
                        "currency": "SEK"
                    }
                ]
            },
            {
                "id": 22565423394,
                "title": "Litware Wireless Mouse M35",
                "imageUrl": "/images/22565423394.png",
                "url": "/products/22565423394",
                "prices": [
                    {
                        "amount": 239.6,
                        "currency": "SEK"
                    }
                ]
            }
        ];

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

</script>
</body>
</html>

You have the capability to set the total for each item directly within the HTML section and then perform the total calculation in the JavaScript part with these modifications as demonstrated below,

In HTML:

`{{total[$index]=product.prices[0].amount * product.quantity}}`

In JS:

$scope.total=[];

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

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

Issue encountered while transferring SQL Server data to user interface

Hello and I hope you're having a great day :). Currently, I am working on pulling data from SQL server to my react project. I have successfully retrieved the data in json format to be displayed on localhost:5000 (where my server.js is running). I hav ...

Finding the row index in an Angular material table

How can I retrieve the row index in an Angular material table? <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()&quo ...

Having trouble with the API authentication call, receiving a "Failed to load resource: net::ERR_CONNECTION_REFUSED" error message

I am facing an issue with my Vue and .net application. Whenever I run "NPM start serve," it successfully builds the app. The app is running locally at: http://localhost:8080/ However, when I attempt to log in, I encounter the following error: Console err ...

How can you retrieve attributes from a specific element within a dropdown menu?

I came across this intriguing HTML code snippet: <select id="selectSomething"> <option id="4" data-name="tomato" data-email="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfbba0a2aebba08fbbe1aca0a2">[email ...

JavaScript - analyzing multiple arrays against a single array

Can anyone help me determine whether 'buns' or 'duns' has the most elements in common with 'me'? I need a method to accomplish this task. var buns = ['bap', 'bun', 'bop']; var duns = ['dap&a ...

Javascript clock problem, kick off on click

Currently working on a game and in need of a counter that starts when clicked and stops at 00 (From 1m to 00). It is currently starting onload and cycles back to start when it reaches 00. HTML: <body> <div> <div class="timer" >Battle t ...

Issue with callback and logic in Angular 2.0 form handling

As a beginner in Angular, I am attempting to develop a simple script that updates the price when the value of a form input changes. There are various methods for utilizing Angular with class-driven and directive-driven models. Despite reading the documenta ...

Which extractor works most effectively with a JSON message in JMeter?

Currently, I am in the process of testing a system that generates output in formatted JSON. During my tests, I need to extract and validate two specific values from the JSON data. Both values have unique identifiers but are located in different parts of t ...

Ways to add values to a database through modal window

There are two buttons on the interface: login and register. Clicking the login button opens the login modal, while clicking the register button should open the register modal. My objective is to validate the form and insert the values into a database aft ...

adding the fresh json information to the current json collection

Trying to incorporate JSON data into another list of JSON data using the update function. Samples: data = {'name':{'first' : 'xx', 'last': 'yy'}, 'class': {'standard': '5', ...

Switch from using fetch to utilizing axios for making API requests

I used fetch for a 'get' request, but now I want to switch to axios. Can someone please help me convert this code to use axios instead? More details: I am fetching an image and using the blob method to display it to the user. I would like to ach ...

JavaScript : Retrieve attributes from a JSON object

Situation : I have a JSON object with multiple properties and need to send only selected properties as a JSON string to the server. Approach : To exclude certain properties from the JSON string, I utilized the Object.defineProperty() method to set enumera ...

Utilizing Ajax in PHP to handle post requests and gracefully handle errors

I have retrieved data from a database and I am presenting it in a pie chart using chartjs. My goal is to allow the user to select a specific range of dates. When the user clicks the filter button, the pie chart should update to display data based on the s ...

Ways to retrieve images for various pixel densities from a server

In my activity, I have an expandableListView where I am fetching data from a JSON obtained from the server. Everything works smoothly except for the image display. The image path is returned as a string in the JSON for various sizes (48x48, 72x72, 96x96, e ...

Ways to convert all keys to uppercase in an array of objects?

Is there a way to capitalize the first letter of every key in an array of objects? I attempted to achieve this with the code below, but it's not working as expected. Any suggestions or corrections are appreciated. #current code function capitalizeO ...

JavaScript Regular Expression for standardizing phone number input

I'm working with an input for a phone number in French format which can accept two different formats: 0699999999 +33699999999 There is currently no check for the length of the number. In the database table, the field is varchar 12, but shorter inp ...

Having trouble displaying Json data on an HTML page?

I am trying to incorporate a local JSON file into an HTML page using JavaScript. I have successfully loaded the data from the JSON file into the console, but I'm encountering issues when trying to display it on the HTML page. Could someone please revi ...

Developing ES6 modules in C++ using Node.js

Here is a previous example showcasing how to create a Node.js addon in C++: https://nodejs.org/api/addons.html You can use node-gyp to build it into a common JS module, which works well with the 'require' function. However, when trying to impo ...

Do we require 'function()' when declaring an event?

I currently have two scripts included in my project: <script src="../js/createopp.min.js"></script> <script src="../js/validation.min.js"></script> Within the first script, there is a line calling a function from the second script ...

Getting state from two child components in React can be achieved by using props to pass the

In my tabbed modal dialog, I have two image list components rendering images based on props defined in the parent. Each component manages its own array of image objects. The challenge is that I need to update or delete these images using a single save butt ...