There is such a 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); } } 

The task is elementary, but I can’t figure out how to calculate the final amount? Jsbin example

    1 answer 1

    Add something like this to the controller:

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

    and in markup, respectively,

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