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

Failure to retrieve blob - net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK)

My fetch request code in my front end for a node js express web app hosted on MS Azure works well for small zip file blobs. However, it times out and displays the error net::ERR_CONTENT_LENGTH_MISMATCH 200 (OK) when dealing with large blobs. ...

Utilizing timezones with Moment.js

Currently, I am utilizing momemt.js and moment-timezone.js to present time in the browser. At this time, I have received epoch time from the server which has been converted to central time. My goal now is to exhibit the time in EST/EDT format. To achieve t ...

How One Simple Click Can Impact Every Button in jQuery Ajax操作

Whenever I try to click a button that should only affect a specific id, it ends up affecting every button on the page by sending data to our API as well. You can check out a snapshot of my page here. Each row has a unique id, but when I click the vote butt ...

Challenges with Media Queries post Integration of MUI Library in React

I have been scratching my head for the last few hours. I needed to utilize a react library to design my dog app for a project. Opting for the MUI library, it has been effective for the grid layout. However, the challenge arises when attempting to implement ...

Tips for loading a webpage when a button is clicked with the help of jQuery AJAX and PHP:

Is it possible to dynamically load a page on button click, pass data to the new page using jQuery AJAX, and place the received value in an input field within the loaded page? Basically, the scenario is as follows: A button named "Something" triggers the l ...

Adjusting the size of HighCharts HighMaps with a custom function

Simple query here (I believe) I have a DIV with the class "container" acting as my Map. The Highcharts plugin I'm using is responsive, but it only resizes when the window does. I'm looking to manually trigger a resize without adjusting my windo ...

Issues with AngularJS ng-repeat functionality

Hey there! I'm encountering an issue with accessing data from a table using ng-repeat in my code. Even though everything seems correct, the data doesn't load when I view the page. Here's a snippet of my table setup: <table class="table t ...

What are the best methods for improving the efficiency of a leaflet route

My map displays a path with more than 13,000 latitude and longitude points. When testing locally, everything works well. However, once the app is on a device, it becomes extremely slow and laggy. The density of the path is due to snapping it to roads. Wha ...

Error encountered in AngularJS due to an unexpected token found in JSON data at position 97 while trying to parse it

Here is the data I received {"contacts":[{"id":"1","company":"Cutting","contact":"Russell Chimera"},{"id":"2","company":"Gge's","contact":"Marci"}]} When processing this, I encountered an issue A syntax error occurred: Unexpected token ' in ...

JavaScript Functions for Beginners

I'm currently facing some challenges with transferring the scripts and HTML content from the calendar on refdesk.com. My task involves moving the JavaScript to a separate stylesheet and utilizing those functions to replicate the calendar on an HTML pa ...

When utilizing Vue components, the issue of "setattr" arises when trying to assign

Having recently started using Vue.js, I encountered an issue while trying to implement components. Interestingly, the code worked perfectly fine before implementing components. I'm facing an error that is proving to be quite challenging to understand ...

Resetting the check status in html can be accomplished by using the checked

I am currently working on a popup feature in HTML <div id="term_flags" class="term_flags"> <div class="modal-users-content flagsContent"> <div class="modal-users-header"> <span class="close" ng-clic ...

jQuery's Offset().left is experiencing some issues and not functioning correctly

Do you have a question about the jQuery offset() function? On my website, I utilize it to show an "email a friend" window when the email icon is clicked. However, the problem is that the window ends up stuck to the right side of the browser's window ...

NPM - Include in package.json without installation

Can a command be executed to validate that the package is a legitimate npm package, include it as a dependency in package.json, but refrain from actually installing it? This question arises from the need to utilize a specific package globally and incorpor ...

Encountering an issue when trying to send data with Axios client to the child component

I'm encountering an issue while attempting to pass data to a child component for rendering. import axios from 'axios'; import React from 'react'; import MovieCard from './MovieCard'; import { useState, useEffect } from ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

How to query the entire MongoDB collection with Node.js

I am looking to create a full search functionality in my MongoDB collection using Node.js. How can I modify the SaleModel.find() function to search for a value across the entire collection? Currently, my implementation only searches the 'product_name ...

Is there a way to use jQuery to enable multiple checkboxes without assigning individual IDs to each one?

I need help finding a way to efficiently select multiple checkboxes using jQuery without relying on individual ids. All of my checkboxes are organized in a consistent grouping, making it easier for me to target them collectively. To illustrate my issue, I ...

Incorporating a JavaScript npm module within a TypeScript webpack application

I am interested in incorporating the cesium-navigation JavaScript package into my project. The package can be installed via npm and node. However, my project utilizes webpack and TypeScript instead of plain JavaScript. Unfortunately, the package is not fou ...

AWS Lambda Error: Module not found - please check the file path '/var/task/index'

Node.js Alexa Task Problem Presently, I am working on creating a Node.js Alexa Skill using AWS Lambda. One of the functions I am struggling with involves fetching data from the OpenWeather API and storing it in a variable named weather. Below is the relev ...