Dorota Dorota - 3 months ago 29
AngularJS Question

add an item to cart

I'm making a small app that searches an item from list, displays it's price and multiplies it by the quantity. Below that I added an add button. Now I want the item with its price and quantity to add under the button (to make something like a shopping cart, basically), but I'm struggling with the code, it doesn't work.

Here's the code:

<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-cloak>
<head>
<meta charset="utf-8">
<title>app</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-messages.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc.5/angular-material.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc.5/angular-material.min.css">
<link rel="stylesheet" href="./style.css" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700,400italic, 700italic' rel='stylesheet' type='text/css'>
</head>
<body layout="column" ng-controller="autoCompleteController">
<div>
<h1>Purchase Order</h1>
<div>
<div layout="row">
<div flex><h4>Name</h4></div>
<div flex><h4>Quantity</h4></div>
<div flex><h4>Price</h4></div>
<div flex><h4>Total</h4></div>
</div>
<div layout="row">
<div flex>
<md-autocomplete flex
md-selected-item="selectedItem"
md-search-text="searchText"
md-items="item in querySearch(searchText)"
md-item-text="item.name"
placeholder="Product name"
md-min-length="0">
<span md-highlight-text="searchText">{{item.name}}</span>
</md-autocomplete>
</div>
<div flex>
<md-input-container md-no-float class="md-block">
<input ng-model="quantity" placeholder="Quantity">
</md-input-container>
</div>
<div flex><p>{{selectedItem.price}}</p></div>
<div flex><p>{{quantity * selectedItem.price}}</p></div>
</div>
<div>
<p>{{jsonCartItem.name}}</p>
<p>{{jsonCartItem.price}}</p>
<p>{{jsonCartItem.qty}}</p>
<p>{{jsonCartItem.totAmt}}</p>
</div>
<md-button class="md-raised" ng-click="AddInCart()">Add item</md-button>
</div>
</div>
<script src="../src/api.js"></script>
</body>
</html>


and JS:

var myApp = angular.module('myApp', ['ngMaterial']);
myApp.controller('autoCompleteController', function($scope) {
$scope.querySearch = function() {
return $scope.products.filter(p => p.name.toLowerCase().includes($scope.searchText));
};
$scope.AddInCart = function() {
var itemName = $scope.products.name;
var itemPrice = parseInt($scope.products.price);
var itemQty = parseInt($scope.quantity);
var totalPrice = parseInt(itemPrice * itemQty);
var jsonCartItem = {
'name' : itemName,
'price' : itemPrice,
'qty' : itemQty,
'totAmt' : totalPrice
};
$scope.products.push(jsonCartItem);
};

$scope.products = [
{name:"Worn Shortsword",price:3}
/*4000 other products here */
,{name:"Annealed Blade",price:12980}
];
});


I would be very grateful if anyone could point me what I'm doing wrong.

Here's the codepen: http://codepen.io/summerfreeze/pen/VjqJYW

Answer

var myApp = angular.module('myApp', ['ngMaterial']);
    myApp.controller('autoCompleteController', function($scope) {      
      $scope.selectedItems = [];
        $scope.querySearch = function() {
            return $scope.products.filter(p => p.name.toLowerCase().includes($scope.searchText));
        };
        $scope.AddInCart = function() {
            var itemName = $scope.selectedItem.name;
            var itemPrice = parseInt($scope.selectedItem.price);
            var itemQty = parseInt($scope.quantity);
            var totalPrice = parseInt(itemPrice * itemQty);
            var jsonCartItem = {
                'name' : itemName,
                'price' : itemPrice,
                'qty' : itemQty,
                'totAmt' : totalPrice
            };
            $scope.selectedItems.push(jsonCartItem);
          console.log($scope.selectedItems);
        };

        $scope.products = [
    {name:"Worn Shortsword",price:3}
    ,{name:"Bent Staff",price:4}
   ,{name:"Worn Mace",price:3}
   ,{name:"Worn Axe",price:3}
             ,{name:"Revelosh's Armguards",price:4500}
   ,{name:"Revelosh's Spaulders",price:6725}
   ,{name:"Revelosh's Gloves",price:4534}
   ,{name:"The Shoveler",price:16164}
   ,{name:"Annealed Blade",price:12980}
];
    });
body {
    max-width: 720px;
    background: #eee;
    margin: 2em auto;
    font-family: 'Open Sans', sans-serfi;
}

div.row > * {
    width: 24%;
    display: inline-block;
}

div.row {
    position: relative;
}


div.row > *:nth-child(n + 3) {
    text-align: right;
}

button {
    margin-top: 1em;
}

input {
    padding: 0.4em;
}

md-autocomplete {
    width: 80%;
}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-aria.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-messages.min.js"></script>
 <script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.js"></script>

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0-rc2/angular-material.min.css">
  
 <html lang="en">
   <body  ng-app="myApp" ng-cloak ng-controller="autoCompleteController" layout="column" >
      <div>
     <h1>Purchase Order</h1>
      <div>
        <div layout="row">
          <div flex><h4>Name</h4></div>
          <div flex><h4>Quantity</h4></div>
          <div flex><h4>Price</h4></div>
          <div flex><h4>Total</h4></div>
        </div>
        <div layout="row">
          <div flex>
           <md-autocomplete flex 
              md-selected-item="selectedItem" 
              md-search-text="searchText" 
              md-items="item in querySearch(searchText)"
              md-item-text="item.name" 
              placeholder="Product name"
              md-min-length="0">
          <span md-highlight-text="searchText">{{item.name}}</span>
      </md-autocomplete>
          </div>
          <div flex>
          <md-input-container md-no-float class="md-block">
          <input ng-model="quantity" placeholder="Quantity">
        </md-input-container>
          </div>
          <div flex><p>{{selectedItem.price}}</p></div>
          <div flex><p>{{quantity * selectedItem.price}}</p></div>
        </div>
        <div>
                       <p>{{jsonCartItem.name}}</p>
                       <p>{{jsonCartItem.price}}</p>
                       <p>{{jsonCartItem.qty}}</p>
                       <p>{{jsonCartItem.totAmt}}</p>
        </div>
        <md-button class="md-raised" ng-click="AddInCart()">Add item</md-button>
      </div>
      <h4>Added Items</h4>
      <table>
        <tr ng-repeat="item in selectedItems">
          <td>{{item.name}}</td>
          <td>{{item.qty}}</td>
          <td>{{item.totAmt}}</td>
        </tr>
      </table>
</div>
   <script src="../src/api.js"></script>
  </body> 

As @Dinesh Shah explained, you can access array elements only by using index.

One more mistake what I could see is when clicking on "add to cart" button, you are trying to push "jsonCartItem" into the master collection "$scope.products" which is wrong.

"$scope.products" is the master collection of items.

You should initialise one more scope variable something like below

$scope.addedItems = [];

and then probably

$scope.addedItems.push(jsonCartItem);