1

Есть такой Shopping Card HTML:

  <body ng-app="shopApp" ng-controller="ProductsController as ctrl">
     <h2>Shopping Card Example</h2>
     <div>
       <table class="table">
         <tr>            
           <th>name</th>
           <th>Cost</th>
           <th>Qty</th>
           <th>Total</th>
        </tr>
        <tr ng-repeat="product in ctrl.products">
          <td><input type="text"  ng-model="product.name"></td>           
          <td><input type="number"  ng-model="product.price"></td>
          <td><input type="number" min="1" max="5" step="1" ng-model="product.quantity"></td>
        <td>{{product.quantity * product.price}}</td>
        <td>
           [<a href ng-click="ctrl.removeItem($index)">X</a>] 
        </td>
    </tr>
    <tr>
        <td><a href ng-click="ctrl.addItem()" class="btn btn-small">add item</a></td>
        <td></td>
        <td>Total:</td>
        <td></td>
    </tr>
</table>
</div>

</body>

js:

     var app = angular.module('shopApp',[]);
     app.controller('ProductsController', ProductsController);


   function Product(id, name, price, quantity){
     this.id = id;
     this.name = name;
     this.price = price;
     this.quantity = quantity; 
   }

   function ProductsController() {
     this.products = [
         new Product(1, "Milk", 33, 1),
         new Product(2, "Apple", 23, 1),
         new Product(3, "Tea", 36, 1),
      ];

  this.addItem = function() {
     this.products.push({
         quantity: 1,
         name: '',
         price: 0
        });
     },

   this.removeItem = function(index) {
       this.products.splice(index, 1);
             }
   }

Задача как бы элементарная, но никак не могу придумать, как правильно посчитать итоговую сумму? Пример на jsbin

1 ответ 1

0

Добавьте в контроллер что-нибудь вроде этого:

this.getTotal = function() {
    return this.products.reduce(function (prev, item) {
      return prev + item.price * item.quantity;
    }, 0);
  }

а в разметку, соответственно,

<td>{{ctrl.getTotal()}}</td>

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.