How to Create Calculator in AngularJS

Are you searching for a tutorial to create a standard calculator web app using AngularJS? Hopefully, you are at the right place. In this tutorial, I will guide you step by step on how to create a standard and stylish calculator using AngularJS. In order to understand the concepts in this tutorial, you must at least know the basics of Javascript, HTML, and CSS.

HTML Template for Calculator:
<!doctype html>
<html>
<head>
<title>AngularJS Calculator</title>
<script src="lib/angular.min.js"></script>
<script src="scripts/angularCalculator.js"></script>
<link rel="stylesheet" href="styles.css"/>
</head>
<body ng-app="calculator" ng-controller="calculatorCtrl">
<div class="whole-container">
<div class="result-container">
{{firstValue || 0 }}
<span ng-if="currentModifier">{{currentModifier}}</span>
<span ng-if="secondValue">{{ secondValue }}</span>
<span ng-if="result" class="result-item"> = {{ result }}</span>
<button class="clear-button" ng-click="clearNumbers()">X</button>
</div>
<div class="number-modify-container">
<div class="number-container">
<div class="number-inner-container" ng-repeat="num in numArr">
<button class="number-item" ng-click="showNumber(num)">{{ num }}</button>
<button class="number-item" ng-if="$index == 9" ng-click="showNumber('.')"> . </button>
</div>
</div>
<div class="modify-container">
<button class="modify-item" ng-repeat="mod in modifiers" ng-click="makeSecondValue(mod)">{{ mod }}</button>
</div>
</div>
<button class="result-button" ng-click="doMath()">=</button>
</div>
</body>
</html>
The above HTML contains several AngularJS built-in directives like ng-app, ng-controller, ng-if, ng-repeat, ng-click etc. If you don’t know their usage in our HTML, don’t worry, I had explained their usage in this tutorial.
Create Calculator Logic in AngularJS
AngularJS is the most popular JavaScript library developed by Google. To include AngularJS library to your project, refer the AngularJS file like below or use CDN in your HTML. Download AngularJS
<script src="lib/angular.min.js"></script>
Calculator Module in AngularJS
AngularJS modules are containers of different parts of your app such as controllers, services, filters etc. Create a file (angularcontroller.js) to write our AngularJS code.
var app = angular.module("calculator", []);
<body ng-app="calculator">
To bootstrap/start your AngularJS, use AngularJS built-in ng-app directive as with your module name as value.
Create Calculator Controller
Controllers in AngularJS are the glue to our View (HTML). In order to create a controller in AngularJS, you should use the AngularJS controller() method on your module.
var app = angular.module("calculator");
app.controller("calculatorCtrl",function($scope) {
//Our code goes here....
});
Controller method has two parameters, the name of the controller and the callback function with the $scope object as a parameter. $scope object is the glue stick to the HTML. In other words, whatever properties and methods we add to the $scope is readily available to the HTML. This makes it easy to get started with AngularJS.
<body ng-app="calculator" ng-controller="calculatorCtrl">
To set the controller of our app to the view (HTML), use built-in ng-controller directive with the controller name (in this case “calculatorCtrl”) as value.
Create Variables in the controller:
app.controller("calculatorCtrl",function($scope) {
$scope.numArr = [];
$scope.modifiers = ['+','-','*','/'];
$scope.firstValue = "";
$scope.secondValue = "";
$scope.currentModifier = "";
var valueFlag = false;
});
In order to get the user inputs and for the logic flow of our app, I created some global variables, which we are about to use in our functions, with initial values.
- $scope.numArr array holds the numbers 0-9 which we later show in our view (HTML) as buttons.
- $scope.modifiers array contains the arithmetic operators such as addition, subtraction, multiplication, division.
- $scope.firstvalue displays our first input number in our view.
- $scope.secondValue displays our second input value in our view.
- $scope.currentModifier displays the arithmetic operator pressed by the user.
- valueFlag variable acts as a flag to show the first input value and second input value based on some logic.
Create Functions in the controller:
app.controller("calculatorCtrl", function($scope) {
//after our variables
for(var i=9; i >= 0; i--) {
$scope.numArr.push(i);
}
});
Before creating functions, you should create a simple for loop which will add numbers from 0-9 to $scope.numArr in reverse order. In each iteration, push() method pushes the current value of the variable “i”.
function currentValueToShow(num) {
assignValues(num);
}
function assignValues(num) {
if (valueFlag) {
$scope.secondValue += num;
} else {
$scope.firstValue += num;
}
}
$scope.showNumber = currentValueToShow;
function activateFlag() {
valueFlag = true;
}
function setCurrentModifier(modifier) {
activateFlag();
$scope.currentModifier = modifier;
}
$scope.makeSecondValue = setCurrentModifier;
The above code contains several function declarations some of them are later used as function expressions in $scope methods.
<div class="number-inner-container" ng-repeat="num in numArr">
<button class="number-item" ng-click="showNumber(num)">{{ num }}</button>
<button class="number-item" ng-if="$index == 9" ng-click="showNumber('.')"> . </button>
</div>
The ng-repeat built-in directive acts as for-loop inside HTML. It iterates through our $scope.numArr. In each iteration, it creates buttons from 0-9 in reverse order. The ng-click built-in directive is used to handle the click events. In our case, I added the ng-click directive for our buttons with the $scope.showNumber(num) method as value.
Functional Logic of Button Clicks:
When user clicks the number buttons, the $scope.showNumber(num) function is invoked, It checks the state of valueFlag, by default valueFlag is set to false, so the $scope.firstInputValue += num; statement is expressed. If user clicks any of the modifier/arithmetic buttons, the $scope.makeScondValue is invoked. The activateFlag() function will change the state of valueFlag to true. so that when user clicks the number buttons this time, $scope.secondInputValue += num; statement is expressed. The $scope.currentModifier property will get the currently pressed modifier as value.
Give Life to Our Calculator:
function evalMath() {
if($scope.firstValue != '' && $scope.secondValue != '') {
var mathFormat = $scope.firstValue + $scope.currentModifier + $scope.secondValue;
$scope.result = eval(mathFormat);
}
}
$scope.doMath = evalMath;
<button class="result-button" ng-click="doMath()">=</button>
The doMath() function is invoked when the user clicked the = button. It checks all the user input values and then invokes the eval() function in JavaScript. The eval() function is the soul of our calculator. It converts our mathFormat string into JavaScript expression and executes it. The result of the expression is assigned to the $scope.result property.
Show User Inputs and Result in HTML:
<div class="result-container">
{{firstValue || 0 }}
<span ng-if="currentModifier">{{currentModifier}}</span>
<span ng-if="secondValue">{{ secondValue }}</span>
<span ng-if="result" class="result-item"> = {{ result }}</span>
<button class="clear-button" ng-click="clearNumbers()">X</button>
</div>
AngularJS {{ expression }} is used to show $scope property values in HTML. The ng-if built-in directive is used to add or remove the element from the DOM based on the expression as its value.
- 0 is displayed by default until the user presses any of the numeric buttons.
- Once the modifier/arithmetic button is pressed, the “currentModifier” and “secondValue” property values will be displayed along with “firstValue”.
- When the user clicks the = button, the result is displayed along with all the other three values.
- The X button is used to clear the user inputs. The “clearNumbers()” method resets all our variables to its initial value.
Conclusion
I hope that this tutorial helps you to create the calculator you dreamed of. The stylesheet file and the styling methods are not included in this tutorial as it’s out of the scope of this tutorial. I had attached the whole source code for our AngularJS Calculator. If you have any doubts or suggestions, let me know by making a comment below. Thank you.