AngularJS Use Case – Shopping Cart Application
Here we are creating a shopping Cart Application and code for this application is as follows:
<html ng-app='scartApp'><br>
<head><br>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><br>
<title>Shopping Cart</title><br>
</head><br>
<body ng-controller='SCartController'><br>
<h1>Shopping Cart Application</h1><br>
<div><br>
<table border = "1"><br>
<tr><br>
<td><b>Product Name</b></td><br>
<td><b>Quantity</b></td><br>
<td><b>Price</b></td><br>
<td><b>Total Price</b></td><br>
<td><b>Operation</b></td><br>
</tr><br>
<tr ng-repeat="item in items"><br>
<td>{{item.Name}}</td><br>
<td><input ng-model='item.quantity'></td><br>
<td>{{item.price | currency}}</td><br>
<td> {{item.price * item.quantity | currency}}</td><br>
<td><button ng-click="remove($number)">Remove</button></td><br>
</tr><br>
</table><br>
</div><br>
<script><br>
var sapp = angular.module('scartApp', []);<br>
sapp.controller('SCartController', ['$scope', function($scope) {<br>
$scope.items = [<br>
{Name: 'Saree', quantity: 10, price: 100},<br>
{Name: 'Mojari', quantity: 12, price: 40},<br>
{Name: 'Bangles', quantity:8, price: 15},<br>
{Name: 'Jeans', quantity:5, price: 20}<br>
];<br>
$scope.remove = function(number) {<br>
$scope.items.splice(number, 1);<br>
}<br>
}]);<br>
</script><br>
</body><br>
</html><button ng-click="remove($index)">Remove</button><br>
</div><br>
<script src="angular.js"></script><br>
<script><br>
function CartController($scope) {<br>
$scope.items = [<br>
{title: 'Paint pots', quantity: 8, price: 3.95},<br>
{title: 'Polka dots', quantity: 17, price: 12.95},<br>
{title: 'Pebbles', quantity: 5, price: 6.95}<br>
];<br>
$scope.remove = function(index) {<br>
$scope.items.splice(index, 1);<br>
}<br>
}<br>
</script><br>
</body><br>
</html><br>
Output
Watch this Full Stack Web Development Course video
Explanation:
- <html ng-app> – It tells Angular which parts of the page it should handle.
- <body ng-controller=’CartController’> – SCartController will handle everything between <body> and </body>.
- <tr ng-repeat=”item in items”> – It creates an array of item.
- <td>{{item.Name}}</td> – Display Product Name
- <td><input ng-model=’item.quantity’></td> – The ng-model makes data binding between the input field and the value of quantity.
- <td>{{item.price | currency}}</td> – Display the price of item in $ using currency tag.
- <td> {{item.price * item.quantity | currency}}</td> – It displays the total price of the item which is the multiplication of price and quantity.
- <button ng-click=‘remove ($index)’>Remove</button> – Creates a button remove. It will remove the item if you click on this button.
- function SCartController($scope) { } – Manages the logic of this application.
- $scope.items = [ ]; – It defines the collection of item for your shopping cart application.