Automatic calculation in AngularJS based on data from two input fields

My goal is to create a calculator that computes the total of two input fields: price and quantity. I am utilizing AngularJs within the Ionic framework for this project.

Here is my controller.js file:

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope) {
      $scope.a = 0;
      $scope.b = 0;
      $scope.c = $scope.a * $scope.b;
    })

Within my form.html file:

<ion-view view-title="Calculator">
  <ion-content class="padding">
    <div class="list" ng-controller="DashCtrl">
      <label class="item item-input">
        <span class="input-label">Price</span>
        <input type="text" ng-model="a">
      </label>
      <label class="item item-input">
        <span class="input-label">Qty</span>
        <input type="text" ng-model="b">
      </label>
      <label class="item item-input">
        <span class="input-label">Total</span>
        <input type="text" value="{{ c | currency:'Rp ' }}">
      </label>
    </div>
  </ion-content>
</ion-view>

Note:
Price = 5000
Qty = 2
By writing {{ a*b }}, you can easily get Rp 10,000.00 printed on the screen. However, I prefer all calculations to be handled by the controller itself.

What script should I implement in the controller to achieve accurate results?

Answer №1

Utilize the ng-change directive to monitor changes and calculate the sum

<ion-view view-title="Kalkulator">
  <ion-content class="padding">
    <div class="list" ng-controller="DashCtrl">
      <label class="item item-input">
        <span class="input-label">Price</span>
        <input type="text" ng-model="a" ng-change="calculate()">
      </label>
      <label class="item item-input">
        <span class="input-label">Qty</span>
        <input type="text" ng-model="b" ng-change="calculate()>
      </label>
      <label class="item item-input">
        <span class="input-label">Total</span>
        <input type="text" value="{{ c | currency:'Rp ' }}">
      </label>
    </div>
  </ion-content>
</ion-view>

Within the controller

angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope) {
      $scope.a = 0;
      $scope.b = 0;
      $scope.c = $scope.a * $scope.b;
      $scope.calculate = function(){
          $scope.c = $scope.a * $scope.b
      }

    })

Answer №2

To ensure that both 'a' and 'b' fields inputs are updated simultaneously, implement ng-keyup or ng-change functions on both fields and call the same function for both events. Here's an example of how you can set up this functionality:

$scope.updateValues = function() {
    $scope.result = $scope.a * $scope.b;
}

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

Enhance the efficiency of highcharts when handling extensive datasets

I am looking to extract a higher volume of data. Here is a snippet of the sample data: 1850/01 -0.845 -0.922 -0.748 -1.038 -0.652 -1.379 -0.311 -1.053 -0.636 -1.418 -0.272 1850/02 -0.043 -0.113 0.047 -0.244 0.159 -0.613 ...

Is there a method to access the output of getStaticProps function from NextJS API routes?

Is there a method to compute and cache new data during build time that is essential for both the front-end and back-end API routes? I'm looking for a way to access the static properties generated by API routes at build time since the routes are access ...

Obtain ID from a PUT request using Axios in combination with React and Redux

I am facing an issue with making a PUT request to my server. The problem lies in obtaining the identifier for the specific object that needs to be updated. Currently, here is the code that I am working with: import axios from 'axios' import sett ...

Execute HTML code when a button is pressed using Angular

I currently have a basic ng-click button that adds rows with the row and number. What I am looking to do is include a new segment of code like this: <div class="btn btn-info btn-sm" style="display:inline-block" ngf-select="uploadinv($file)">Upload ...

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

Using Vue3 to invoke a method in one component from another component

I'm attempting to call a function from one component to another, specifically from within the setup function. I came across a helpful article on VueMastery which suggests using the following approach: methods: { reset () { this.$refs.count ...

A guide on utilizing radio buttons to delete specific rows within a table with the help of AngularJS

My current issue involves using radio buttons to delete rows in a table. The problem I'm encountering is that multiple rows are being deleted at once instead of just one. You can view an image of my table here. As we all know, with radio buttons, onl ...

How Keyof can render an object undefined and prevent accurate verification

Encountering TS2532 error: Object is possibly 'undefined' while attempting to access an object's value by dynamically selecting the key. TypeScript seems to be restricting me from checking the field values, and I'm unsure of the underly ...

Invoking a non-static method in the server-side using a client-side function

I am trying to retrieve an object from the server side using static receive callbackresult methods. However, my goal is to execute a non-static method on my page to populate an ajax accordion by invoking a client-side function. The object I am fetching f ...

Is it possible to incorporate Javascript into Skeleton framework?

I've run into a bit of confusion while trying to navigate the world of frameworks. Specifically, I'm experimenting with Skeleton (getskeleton.com) for the first time and encountering an issue with a Javascript file. Despite referencing it in the ...

"Troubleshooting: When using the Script tag in EJS, conditional IF statements may not function

I encountered an issue here. I placed a script tag inside an IF conditional statement. However, the script tag runs whether the condition is TRUE or FALSE. For instance: <% if (info) { %> <p><%=info%></p> <scrip ...

Sending data in JSON format using the POST method with Restangular in an AngularJS application

I'm a newcomer to Angular JS and I need to use restangular POST to send form data in JSON format. I'm also unfamiliar with the POST functionalities, can someone guide me on how to achieve this? My Index Page: <form ng-controller="registerCtr ...

Troubleshooting TextField malfunctioning after button click within Dialog on Material UI

My main objective is to focus on a Material UI TextField after closing a Dialog by clicking a button inside the Dialog. The code snippet below successfully accomplishes this task when triggered from a button that is not within a dialog component: focusOn ...

"Troubleshooting why React fails to update an array state

When I click the update name button, the state is not changing properly using setState. I want to update the persons variable and have it reflect in the DOM as well. Any ideas on how to achieve this? App.js import React, { Component } from "react"; impo ...

Navigating through an AngularJS dialog box on a webpage with the help of Selenium

I am encountering an issue with an AngularJS webpage where a prompt appears under specific circumstances. The code needs to ignore the prompt if it doesn't show up, but if it does, it should be accepted using JavaScript. When inspecting with Firebug, ...

The controller's variable does not appear to be updating the user interface as expected

When the HTML page loads, I call a function within an angularjs controller (discussions()), which sets a value to a variable ($rootScope.name). Later, when I click a button on the same HTML page, it triggers a series of JavaScript functions. The final Java ...

Display a series of messages using an Angular directive

Here is a sample HTML code: <section class="correspondence"> <header> <div class="from">{{ message.from }}</div> <div class="when">{{ message.when }}</div> </header> <div class="content"> { ...

Incorporate HTML and JavaScript to dynamically show a button when a specified condition evaluates as true and hide the button if the

I need help with a scenario where I want to show a button only when a specific variable reaches a certain value. For instance, if the variable equals 5, the button should be displayed; otherwise, it should be hidden. Here are the two buttons included withi ...

Trouble with React component not updating after URL parameter change despite utilizing useEffect hook for data fetching

Let's address an important issue: I've created a component that needs to maintain the same structure across approximately 25 different items or pages. To achieve this in React, I am dynamically passing URL parameters into my API request as shown ...