Tutorial #7: Building a Calculator with Angular JS

Posted by


In this tutorial, we will be creating a simple calculator application using AngularJS. AngularJS is a JavaScript-based open-source front-end web application framework that is maintained by Google. It is widely used for building dynamic web applications and is known for its ability to create modular, reusable components.

To get started, make sure you have AngularJS installed in your project. You can include it in your project by downloading the latest version from the official website or using a CDN link.

Now, let’s create a new HTML file and include the AngularJS script like this:

<!DOCTYPE html>
<html>
<head>
    <title>AngularJS Calculator</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
    <div ng-app="calculatorApp" ng-controller="calculatorCtrl">
        <h1>Simple Calculator</h1>

        <input type="number" ng-model="num1" placeholder="Enter first number">
        <input type="number" ng-model="num2" placeholder="Enter second number">

        <button ng-click="add()">Add</button>
        <button ng-click="subtract()">Subtract</button>
        <button ng-click="multiply()">Multiply</button>
        <button ng-click="divide()">Divide</button>

        <h2>Result: {{result}}</h2>
    </div>

    <script>
        var app = angular.module('calculatorApp', []);

        app.controller('calculatorCtrl', function($scope) {
            $scope.add = function() {
                $scope.result = $scope.num1 + $scope.num2;
            }

            $scope.subtract = function() {
                $scope.result = $scope.num1 - $scope.num2;
            }

            $scope.multiply = function() {
                $scope.result = $scope.num1 * $scope.num2;
            }

            $scope.divide = function() {
                $scope.result = $scope.num1 / $scope.num2;
            }
        });
    </script>
</body>
</html>

In this code snippet, we have created a simple calculator application with four basic operations: addition, subtraction, multiplication, and division. We have defined a controller called calculatorCtrl that contains four functions for each operation. These functions will update the result variable with the calculated value.

To run this application, simply open the HTML file in a browser and start entering numbers in the input fields. When you click on any of the operation buttons, the result will be displayed below.

This is a basic example of how AngularJS can be used to create simple interactive applications. You can further customize this calculator by adding more features like decimal support, memory functions, scientific calculations, etc.

I hope this tutorial was helpful in getting you started with creating a calculator application using AngularJS. Feel free to explore more features and functionalities of AngularJS to build more complex and interactive applications. Happy coding!