How to create a basic calculator in AngularJS with two textboxes specifically designed for calculating squares?

My code snippet is as follows:

    <html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>

<body>
  <div ng-app="app">
    <div ng-controller="CalculatorController">
      Enter a number:
      <input type="number" ng-model="number" />
      <br /> Enter a number:
      <input type="number" ng-model="number2" />
      <br />
      <div>
        <button ng-click="doSquare()">X<sup>2</sup></button>
        <button ng-click="doCube()">X<sup>3</sup></button>
      </div>
      <br />
      <div>
        <button ng-click="doAdd()">Add</button>
        <button ng-click="doSubstract()">Subtract</button>
        <button ng-click="doMultiply()">Multiply</button>
        <button ng-click="doDivide()">Divide</button>
        <button ng-click="doModulus()">Modulus</button>
      </div>
      <div>Output: {{answer}}</div>
      <div>
        <button type="button" ng-click="clear('filter')">Clear</button>
      </div>
    </div>
  </div>
  <script>
    var app = angular.module('app', []);

    app.service('MathService', function() {
      this.add = function(a, b) {
        return a + b
      };

      this.subtract = function(a, b) {
        return a - b
      };

      this.multiply = function(a, b) {
        return a * b
      };

      this.divide = function(a, b) {
        return a / b
      };

      this.modulus = function(a, b) {
        return a % b
      };
    });

    app.service('CalculatorService', function(MathService) {

      this.square = function(a) {
        return MathService.multiply(a, a);
      };
      this.cube = function(a) {
        return MathService.multiply(a, MathService.multiply(a, a));
      };
      this.add = function(a, b) {
        return MathService.add(a, b);
      };
      this.subtract = function(a, b) {
        return MathService.subtract(a, b);
      };
      this.multiply = function(a, b) {
        return MathService.multiply(a, b);
      };
      this.divide = function(a, b) {
        return MathService.divide(a, b);
      };
      this.modulus = function(a, b) {
        return MathService.modulus(a, b);
      };
    });

    app.controller('CalculatorController', function($scope, CalculatorService) {

      $scope.doSquare = function() {
        $scope.answer = CalculatorService.square($scope.number);
        $scope.answer = CalculatorService.square($scope.number2);
      }

      $scope.doCube = function() {
        $scope.answer = CalculatorService.cube($scope.number);
        $scope.answer = CalculatorService.cube($scope.number2);
      }
      $scope.doAdd = function() {
        $scope.answer = CalculatorService.add($scope.number, $scope.number2);
      }
      $scope.doSubtract = function() {
        $scope.answer = CalculatorService.subtract($scope.number, $scope.number2);
      }
      $scope.doMultiply = function() {
        $scope.answer = CalculatorService.multiply($scope.number, $scope.number2);
      }
      $scope.doDivide = function() {
        $scope.answer = CalculatorService.divide($scope.number, $scope.number2);
      }
      $scope.doModulus = function() {
        $scope.answer = CalculatorService.modulus($scope.number, $scope.number2);
      }
      $scope.clear = function(answer) {
       $scope.answer = null; 
      }
    });
  </script>
</body>

</html>

I am trying to get the answer by clicking X^2 after entering input in both textboxes. Can someone guide me on how to achieve this? Here's the plunker link for reference: http://plnkr.co/edit/8Y47MDICWdeBTiJzaUnP?p=preview

Answer №1

Is there a way to input values into two separate textboxes and calculate the answer by clicking X^2 for each textbox individually?

You can achieve this using the || (or) operator in your code.

$scope.doSquare = function() {
    $scope.answer = CalculatorService.square($scope.number) || 
                    CalculatorService.square($scope.number2);
}

This solution may not be perfect, but it should address your issue for now.

Keep in mind that this code will only calculate the answer for the first textbox if it has a value entered, without moving on to the second one.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When implementing protractor spyOn() with jQuery's ajax() function, an error is triggered stating 'ajax() method is non-existent'

I am currently testing the functionality of using AJAX to submit a form. Below is the Protractor code for the test: describe('login.php', function() { it("should use ajax on submit", function() { browser.get('/login.php'); spyOn($ ...

How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with. The situation involves a function that takes another function as a parameter: var myfunc = (func_outer) => { return func_outer().func ...

Utilizing TypeORM to selectively choose data in OneToMany relationships

I am looking to create a TypeORM query that pulls data from the database. Specifically, I want to retrieve all clients who have made a purchase but have not initiated a return. Here is the structure of the database: Clients: Id (Int, primary column) Purc ...

Is there a way to modify the separator for ng-tags-input? By default, it is set as

Is there a way to preserve the space character when adding a space-separated tag in ng-tags-input instead of it being replaced with a dash? ...

Navigating the Angular Controller life cycle

I have set up my application states using ui-router: $stateProvider .state('app', { abstract: true, views: { 'nav@': { templateUrl: 'app/navbar.html', controller: 'NavbarController' ...

Get rid of the spaces in web scraping <tr> tags using Node.js

I've encountered a problem that goes beyond my current knowledge. I'm attempting to web-scrape a specific webpage, targeting the <tr> element in nodejs. Although I can successfully retrieve the content, it seems that the format is not as cl ...

Add the cordova plugin multi-image-picker with the following command

onDeviceReady: function() { window.imagePicker.getPictures( function(results) { for (var i = 0; i < results.length; i++) { alert('Image URI: ' + results[i]); } }, function ...

Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls. Check out this directive: gameApp.directive('mapActivity', function() { return { restrict: 'A', link: function(scope, element, att ...

What is the best way to incorporate intervals and polling in Angular 2 for seamless integration with Protractor?

I have an angular2 application that I am looking to test using protractor. Within this application, there is a page featuring a graph that updates at regular intervals with data generated on its own. It appears that one aspect of protractor is the abilit ...

Experience the enhanced features and optimized performance of Onsen 2.0 compared to the earlier version

Apologies if this question is too simplistic, but I am finding some conflicting information in the documentation about using Onsen with Monaca. I am currently utilizing Monaca cloud and I prefer to work solely with pure JS, without incorporating Angular ...

Implementing JSON responses in Express JS

My apologies for any language errors as English is not my first language, I am using Google Translate :) I have a question.. Here is the MySQL Query I am working with: SELECT destinations.*, questions.*, answers.* FROM destinations INNER JOIN questions ...

Module lazily loaded fails to load in Internet Explorer 11

Encountering an issue in my Angular 7 application where two modules, txxxxx module and configuration module, are lazy loaded from the App Routing Module. The problem arises when attempting to navigate to the configuration module, as it throws an error stat ...

"Employing Angular's UI Router for seamless navigation through a Multi-Step Form with thorough

I am currently using UI router and below is the configuration: state('app.requistion', { url: "/requisition", templateUrl: 'order/customer-skills/tmpl/main_requisition.html', title: 'Requisition', ...

VueJS Router error: The variable $route is undefined

Check out my component: const Vue = require("vue/dist/vue.js"); const qs = require("querystring"); module.exports = Vue.component("Page",function(resolve){ console.log(pageRoute); let id = pageRoute.params.id; fetch("/getPage.json",{ ...

Executing a Cron Job several times daily, each and every day

This is my current code snippet: const CronJob = require('cron').CronJob; new CronJob({ cursoronTime: '* * * * *', // every minute onTick: async function() { console.log(&ap ...

Obtaining a return value from a function that involves a series of chained Ajax requests in jQuery

I'm facing an issue with my function that involves chained Ajax requests. Function A and B are both Ajax requests, where A runs first and B runs after A returns its data. The problem arises when Function C executes Function B. Upon execution of Funct ...

Executing an event in Javascript or triggering with Jquery- the process of initiating an event once a value is sent to an input box by Javascript

How do you trigger an event when a JavaScript-passed value is entered into an input box? <!DOCTYPE html> <html> <body> <p>Type something in the text field to activate a function.</p> <input type="text" id="myInput" oninp ...

Executing npm scripts in Node.js

Trying to move away from using the likes of Grunt or Gulp in my projects, I've been exploring npm-scripts as a potential replacement. While npm-scripts makes use of `package.json`, I've found that more advanced build processes require command lin ...

Tips for setting up the Top Menu and Left Side Menu in your system

You're looking to incorporate both the Top Menu and Left Side Menu. The top menu should remain fixed at the top of the page. Implementing the Left Side Menu below the Top Menu has been a challenge. It's currently covering the top menu, which is ...

Various JSON Tag values occurring more than once

Upon receiving a JSON Object in HTML, I am passing it to a JavaScript function defined below. The issue arises when the same folderName appears repeatedly on the HTML page. JSON Object: { "folderName": "arjunram-test", "objects": [ { ...