AngularJS Tip Calculator
by Guddu Kumar
HTML
<div ng-app="TipApp" ng-controller="TipController">
<h1>Tip Calculator</h1>
<p>
Subtotal: <input id="subtotal" ng-model="subtotal" type="number" placeholder="Amount" autofocus="true" autocomplete="off">
<input ng-click="clearSubtotal();" type="button" value="Clear">
</p>
<p>Tip percentage: <select ng-model="tipRate" ng-options="tipRate | percentage for tipRate in tipRates"></select></p>
<p>Number in party: <select ng-model="split" ng-options="num for num in splits"></select></p>
<div ng-cloak ng-if="subtotal">
<hr>
<table>
<tbody>
<tr>
<td>Subtotal</td>
<td>{{ subtotal | currency }}</td>
</tr>
<tr>
<td>+ {{ tipRate | percentage }} tip</td>
<td>{{ tip() | currency }}</td>
</tr>
<tr>
<td>Total</td>
<td class="separator-above">{{ total() | currency }}</td>
</tr>
<tr ng-if="split > 1">
<td>÷</td>
<td>{{ split }}</td>
</tr>
<tr ng-if="split > 1">
<td>Per person</td>
<td class="separator-above">{{ perPersonTotal() | currency }}</td>
</tr>
</tbody>
</table>
</div>
</div>
CSS
body {
font-family: sans-serif;
}
input[type="number"] {
width: 8em;
}
td {
text-align: right;
padding: 0.5em;
}
.separator-above {
border-top: 1px solid #999;
}
JavaScript
angular.module('TipApp', [])
// Convert a number like 0.15 to a string like "15%"
.filter('percentage', function() {
function percentage(number) {
return (number * 100) + "%";
}
return percentage;
})
.factory('focusElementById', ['$window', function($window) {
function focusElementById(id) {
$window.document.getElementById(id).focus();
}
return focusElementById;
}])
.controller('TipController', ['$scope', 'focusElementById', function($scope, focusElementById) {
debugger
$scope.tipRates = [0.15, 0.18, 0.20, 0.25];
$scope.tipRate = $scope.tipRates[0];
$scope.splits = [1, 2, 3, 4, 5, 6, 7, 8];
$scope.split = 1;
$scope.tip = function() {
return $scope.subtotal * $scope.tipRate;
debugger
};
$scope.total = function() {
return $scope.subtotal + $scope.tip();
};
$scope.perPersonTotal = function() {
return $scope.total() / $scope.split;
};
$scope.clearSubtotal = function() {
$scope.subtotal = '';
focusElementById('subtotal');
};
}]);