2016-11-24 3 views
0

У меня есть этот список продуктов, как JSon объектВычислить Общую стоимость Динамически в угловых

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

и это мой нг-повтор код

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

Общая сумма изменчива, когда пользователь изменить количество.

Есть ли способ получить общую сумму во всех продуктах динамически?

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

ответ

4

Я быстро взломал пример, основанный на вашем коде.

Две вещи:

  1. Использование product.quantity вместо того, чтобы просто quantity.

  2. Просмотреть функцию контроллера calcTotal() для расчета общего количества.

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

+0

Спасибо за ваш ответ. Это спасло меня – shinta

1

Добавить функцию в контроллер, такой как totalPrices() что будет подытожить ваши цены каждого продукта. Кроме того, вы захотите, чтобы quantity был отдельно от каждого продукта, таким образом, он может использоваться при расчете общего количества. Тогда для расчета общих вы можете сделать:

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

Просто обратите внимание, если вы добавите больше элемента в массив цен вам потребуется еще один вложенный цикл для каждого элемента. Ниже приводится измененный HTML с дополнительным контроллером и изменения, как работает качество:

<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

+0

Спасибо :) ваш код работает также – shinta

1

Вы могли бы сделать что-то вроде этого,

<!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(){ 
 
     \t $scope.totalled=0; 
 
     \t for(var i=0;i<$scope.total.length;i++){ 
 
     \t \t $scope.totalled=$scope.totalled+$scope.total[i]; 
 
     \t } 
 
     \t return $scope.totalled; 
 
     } 
 
    }]); 
 

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

Вы можете присвойте общее количество для каждого элемента непосредственно в html-части, а затем выполните общий расчет в js-части с помощью этих изменения, как показано ниже,

В HTML:

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

В 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; 
     } 
Смежные вопросы