AngularJS Shopping Cart

Add/remove items to a shopping cart.

by Rob Rothe

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
<div ng-app="myApp" ng-controller="MyCtrl" class="container">
  <div class="row">
    <div class="col-sm-8">
      <table class="table">
        <tr ng-repeat="product in products">
          <td>
            <button class="btn btn-success btn-block" ng-click="addToCart(product)">
              {{ product.name }} {{ product.price | currency }}
            </button>
          </td>
        </tr>
      </table>
    </div>
    <div class="col-sm-4">
      <div class="well well-sm">
        <h3>
         <span class="fa fa-shopping-cart"></span>
         <div class="pull-right">{{ cartTotal | currency }}</div>
        </h3>
        <p>
          Total Items: {{ cart.length }}
        </p>
        <table class="table">
          <tr ng-repeat="item in cart track by $index">
            <td width="20">
              <button class="btn btn-link btn-remove" ng-click="removeFromCart(item)">
                &times;
              </button>
            </td>
            <td>{{ item.name }}</td>
            <td class="text-right">{{ item.price | currency }}</td>
          </tr>
        </table>
      </div>
    </div>
  </div>

CSS

h3 {
  margin-top: 0;
}

.container {
  margin-top: 20px;
}

.btn-remove {
  outline: none !important;
  padding: 0;
  position: relative;
  top: -4px;
  font-size: 16px;
  color: red;
}

JavaScript

angular
  .module('myApp', [])
  .controller('MyCtrl', MyCtrl);

function MyCtrl($scope) {
  $scope.products = [{
    name: 'Apple',
    price: .75
  }, {
    name: 'Banana',
    price: .50
  }, {
    name: 'Grapes',
    price: 1
  }];

  $scope.cartTotal = 0;
  $scope.cart = [];

  $scope.addToCart = function(product) {
    $scope.cartTotal = $scope.cartTotal + product.price;
    $scope.cart.push(product);
  };

  $scope.removeFromCart = function(item) {
    var idx = $scope.cart.indexOf(item);
    $scope.cartTotal = $scope.cartTotal - item.price;
    $scope.cart.splice(idx, 1);
  };
}