Karlo
Karlo

Reputation: 189

Calculate Total Value Dynamically in angular

I have this list of products as json object

[
  {
    "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"
      }
    ]
  }
]

and this is my ng-repeat code

<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>

Total amount is changeable when user change the quantity.

Is there any way to get the total amount in all products dynamically?

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

Upvotes: 0

Views: 5518

Answers (3)

GraveyardQueen
GraveyardQueen

Reputation: 769

You could do something 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 can assign the total for each item directly in the html part and then do the total calculation in the js part with these changes as shown 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;
        }

Upvotes: 1

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

Add a function to your controller such as totalPrices() that will sum up your prices of each product. Also you will want quantity to be apart of each product instead, this way it can be used when calculating the total. Then for calculating the total you can do:

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

Just note if you add more item to the prices array you will need another nested for loop for each item. Below is the changed HTML with an added controller and changes to how quality works:

  <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>

Here is a Plunker Example

Upvotes: 1

Todd Palmer
Todd Palmer

Reputation: 1102

I whipped up a quick example based on your code.

Two things:

  1. Use product.quantity instead of just quantity.

  2. See the controller function calcTotal() to calulate 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>

Upvotes: 4

Related Questions