Sewer on Angular View

I am working on a cart using Angular, during the process I ran into a calculation problem.

In my scenario, I have code similar to

<label>No. of item</label>
<div>{{totalItems}}</div> 


<div ng-repeat="cartElement in currentCartDetails.cartElements">
        <span>{{cartElement.productName}}</span>
        <span>{{cartElement.productCode}}</span>
        <span>{{cartElement.productPrice}}</span>
        <span>{{cartElement.quantity}}</span>
    </div>

What i want add everything something like

 totalItems += cartElement.quantity

I know that there are so many options for displaying a value, for example. using calculation from the server side, iteration per controller

But what I'm looking for when I repeat an object on the watch page is a way to compute it and take advantage of the tow binding.

+4
source share
2 answers

? , calculateTotal, .

$scope.totalItems = 0;
...
$scope.calculateTotal = function(cart){
  $scope.totalItems += cart.quantity;
}
...

<div ng-repeat="cartElement in currentCartDetails.cartElements" ng-init="calculateTotal(cartElement)">
  <span>{{cartElement.productName}}</span>
  <span>{{cartElement.productCode}}</span>
  <span>{{cartElement.productPrice}}</span>
  <span>{{cartElement.quantity}}</span>
</div>
+2

,

1:

HTML:

<div>{{gettotalItems(currentCartDetails.cartElements)}}</div> 

JS:

$scope.gettotalItems = function(cart_data){
  var num = 0;
  for(var i=0;i<cart_data.length;i++) {
      num += cart_data[0].quantity;
  }
  return num;
}

2:

HTML:

<div ng-init="gettotalItems(currentCartDetails.cartElements)>{{totalItems}}</div> 

JS:

$scope.gettotalItems = function(cart_data){
      var num = 0;
      for(var i=0;i<cart_data.length;i++) {
          num += cart_data[0].quantity;
      }
      $scope.totalItems = num;
    }

. , . , .

0

All Articles