0

I'm writing an application where it allows you to add and remove books. It calculates the total value of the book per row. I'm trying to add up all the prices within the $scope.books.price, but i can't seem to wrap my head around how to write the for loop.

The object atrributes are:

  • title:
  • qty:
  • price:

I would like to display the overall total of the prices from the object array and display them in the table header total cell.

How could iterate through the object to capture the prices and to display on the header?

<!doctype html>
<html lang='en' ng-app>
  <head>
   <title>Book Shopping Cart</title>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.7/angular.min.js"></script>
  <script>
    function CartControler($scope) {
      $scope.books = [
        {title: 'Absolute Java',    
            qty: 1, price: 114.95},
        {title: 'Pro HTML5',        
            qty: 1, price: 27.95},
        {title: 'Head First HTML5', 
            qty: 1, price: 27.89}
      ];
      // need help with this portion can't seem to get the prices to print out
      $scope.totalPrice = function() {
        for (i=0; i < $scope.books.length; i++) {
          $scope.totalPrice += $scope.books.price[i];
        }
      }

      $scope.addBook = function (index) {
        console.log("add new book");
        $scope.books.push({title: 'New Book', qty: 1, price: 10.99});
      }

      $scope.removeBook = function(index) {
        $scope.books.splice(index, 1);
      }

    }
  </script>
  <link rel="stylesheet" href="css/ex05.css">
  </head>

  <body ng-controller="CartControler">

    <table>
      <caption><b>My Books</b></caption>
      <thead>
        <tr>
            <th>Title</th>
            <th>Qty</th>
            <th>UnitPrice</th>
            <th>Line Total</th>
            <th>Total {{totalPrice | currency}}</th> <!--I would like to display overall total here-->
        </tr>
      </thead>
      <tbody >
        <tr ng-repeat="book in books">
            <td><input ng-model="book.title"></td>
            <td>
                <input ng-model="book.qty" size="2">
            </td>
            <td>
                <input ng-model="book.price" >
            </td>
            <td>{{book.price * book.qty | currency}}</td>
            <td>
                <button ng-click="removeBook($index)">
                    Remove
                </button>
            </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th>
            <button ng-click="addBook($index)">New</button>
          </th>
          <th></th>
          <th></th>
          <th>
            <button ng-click="">Save</button>
          </th>
          <th></th>

        </tr>
      </tfoot>
    </table>
  </body>
</html>
  • Seriously, AngularJS? I would suggest you to work with Angular latest version, as it has a loads of newly added improvements and with a huge difference from AngularJS. If you are just beginning with this code, better change asap. All the best! :) – gsthina Apr 06 '20 at 19:25
  • Well, I'm learning AngularJS now and will be moving to Angular. I just need some help understanding this concept. Would you be able to assist? @gsthina – TheOneWhoIsLost Apr 06 '20 at 19:27

1 Answers1

0

Initialize $scope.totalPrice using the current books prices (no need for it to be a function), then use addBook and removeBook functions to update $scope.totalPrice.

EDIT:

Since $scope.totalPrice will be affected in several ways, not just adding and removing books, but also changing a book's quantity and price, then it's necessary to execute the update code in several places. Like this:

function CartControler($scope) {
      $scope.books = [
        {title: 'Absolute Java',    
            qty: 1, price: 114.95},
        {title: 'Pro HTML5',        
            qty: 1, price: 27.95},
        {title: 'Head First HTML5', 
            qty: 1, price: 27.89}
      ];
     
      $scope.addBook = function (index) {
        const newBook = {title: 'New Book', qty: 1, price: 10.99};
        $scope.books.push(newBook);
        $scope.totalPrice += newBook.price  * newBook.qty;
      }

      $scope.removeBook = function(index) {
        const bookToRemove = $scope.books[index];
        $scope.books.splice(index, 1);
        $scope.totalPrice -= bookToRemove.price * bookToRemove.qty;
      }
      
      $scope.updateTotal = function() {
        $scope.totalPrice = 0;
        for (i=0; i < $scope.books.length; i++) {
            $scope.totalPrice += ($scope.books[i].price * $scope.books[i].qty);
        }
     }
     
           $scope.updateTotal()

    }
<!doctype html>
<html lang='en' ng-app>
  <head>
   <title>Book Shopping Cart</title>

 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.7/angular.min.js"></script>

  <link rel="stylesheet" href="css/ex05.css">
  </head>

  <body ng-controller="CartControler">

    <table>
      <caption><b>My Books</b></caption>
      <thead>
        <tr>
            <th>Title</th>
            <th>Qty</th>
            <th>UnitPrice</th>
            <th>Line Total</th>
            <th>Total {{totalPrice | currency}}</th> <!--I would like to display overall total here-->
        </tr>
      </thead>
      <tbody >
        <tr ng-repeat="book in books">
            <td><input ng-model="book.title"></td>
            <td>
                <input ng-model="book.qty" size="2" ng-change="updateTotal()">
            </td>
            <td>
                <input ng-model="book.price" ng-change="updateTotal()">
            </td>
            <td>{{book.price * book.qty | currency}}</td>
            <td>
                <button ng-click="removeBook($index)">
                    Remove
                </button>
            </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th>
            <button ng-click="addBook($index)">New</button>
          </th>
          <th></th>
          <th></th>
          <th>
            <button ng-click="">Save</button>
          </th>
          <th></th>

        </tr>
      </tfoot>
    </table>
  </body>
</html>
Scaramouche
  • 3,188
  • 2
  • 20
  • 46
  • Thank you! That way is much easier than expected. I was over thinking it. – TheOneWhoIsLost Apr 06 '20 at 19:32
  • @TheOneWhoIsLost no problem. Regarding language choice, it's just that, a choice, whatever fits the needs of your project. One thing is true though, if you plan on moving to Angular2+ and are just using AngularJS (<2) to get a starting point, then don't. AngularJS and Angular2+ have NOTHING in common, at least nothing that's worth the effort, if anything you'll end up having even a harder time when transitioning because, I repeat, two completely different worlds. – Scaramouche Apr 06 '20 at 19:36
  • but i notice the total value isn't updating with the changes in prices or quantities. – TheOneWhoIsLost Apr 06 '20 at 19:40
  • @TheOneWhoIsLost check edit. could use some performance improvements but it works – Scaramouche Apr 06 '20 at 19:53
  • It does work. just trying to understand why it doesn't update. Thank you – TheOneWhoIsLost Apr 06 '20 at 19:54
  • @TheOneWhoIsLost what do you mean *why it doesn't update*. it is updating – Scaramouche Apr 06 '20 at 19:54