AngularJS - Enable user to edit dynamically calculated input

My addition calculator has a simple layout as shown below:

<!DOCTYPE html>
<html ng-app>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js">
</script> 
</head>
<body>    
    <input type="number" ng-model="input1" /> + <input type="number" ng-model="input2" /> = <input type="number" ng-model="input1 + input2" />
</body>
</html>

An example calculation would be: 2 + 3 = 5

Now, I have a new requirement to allow editing in the third input field. When this value changes, it should update the first input dynamically so that the numbers add up correctly. For instance, changing 5 to 6 should result in the following:

3 + 3 = 6

The challenge is that the model of the third input is a calculation which prevents direct editing. I need advice on how to make all three inputs editable while maintaining the required calculation functionality.

Answer №1

To handle the ng-change event for the input elements in a controller, you must write the necessary functionality.

<html ng-app="app">
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.js">
</script>
</head>
<body ng-controller="ctrl">
    <input type="number" ng-model="input1" ng-change="calc()"/> + <input type="number" ng-model="input2" ng-change="calc()"/> = <input type="number" ng-model="result" ng-change="recalc()" />
</body>

<script type="text/javascript">

  angular.module('app',[]).controller('ctrl',function($scope){

    
    $scope.recalc = function(){

      $scope.input1 = $scope.result - $scope.input2;

    };

    $scope.calc = function(){
      $scope.result = $scope.input1 + $scope.input2;
    }

  });

</script>
</html>

Answer №2

Trying a different method :)

<!DOCTYPE html>
<html ng-app>
<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js">
  </script> 
</head>
 <body>    
  <input type="number" ng-model="input1" ng-change="answ1=input1+input2" /> + 
  <input type="number" ng-model="input2" ng-change="answ1=input1+input2" /> = 
  <input type="number" ng-model="answ1" ng-change="input1=answ1-input2" />
 </body>
</html>

If you modify any of the input fields, it will immediately show the updated result...

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

Stacking SetIntervals on top of each other

I've been working on a project that involves using setInterval, but I'm struggling to grasp how it functions. The issue I'm encountering is that every time I invoke setInterval, the function appears to be stacking on top of one another, caus ...

Utilizing Visual Studio Code to efficiently eliminate unnecessary imports in an AngularJS project in one go

My current assignment involves tidying up our AngularJS project by eliminating any unused imports and variables. I typically use VS Code along with the TypeScript Hero extension (available at this link) to tackle this task one file at a time. But, I'm ...

Understanding how to utilize and manipulate this JSON data using JavaScript

In my code, there is a variable that contains the following data: { "Rows": [ { "New":1, "CachedNumberType":0, "Date":1327479615921, "Type":2, "Number":"123456", "Duration ...

Having trouble choosing an option from the dropdown menu in bootstrap

I'm experiencing an issue with a bootstrap dropdown that I created. I am unable to select an item from it. The code is shown below: var aos = ''; $('.dropdown-item').click(function(event) { event.preventDefault(); // Prevents ...

Having trouble configuring and executing Vue.js within Laravel

I am fairly new to vue.js but I have experience with laravel. With the recent release of laravel 5.3, I decided to try running a sample application using Vue. resources/js/app.js : /** * First we will load all JavaScript dependencies for this pr ...

Payment authorization through Paypal opens in the parent window instead of a popup window

I have a web application and I am looking to implement the following flow: Merchants log in to PayPal as described here. I obtain the authorization code and exchange it for an access token. With the access token, I make calls to the Payments REST API to ...

Passport sessions do not retain persistence

Having some trouble implementing OAuth 2.0 login where the sessions don't persist after authentication is a common issue. Additionally, there seems to be a problem with the app getting stuck in the routes/bnetauth.js file during the redirect in the ca ...

Replace the empty slots in the array with an underscore

Is it possible to use underscorejs to populate missing elements in an array? For example: fillGaps([1,2,3,6,7,22,23,24]) => [1,2,3,'...',6,7,'...',22,23,24] ...

Discover the correct steps to transition from using particles.js to the react-tsparticles package

Migrating from react-particles-js to react-tsparticles-js Hi there! I'm currently facing an issue with my ReactJS website here, which is deployed using Netlify. The error code below keeps popping up, and I believe it's related to the transition ...

Make a decision within Express.js to select the appropriate middleware modules based on specific conditions

In my express.js endpoint, I am dynamically selecting between middleware callbacks to execute: const middleware1 = require('./m1') const middleware2 = require('./m2') app.get('/call', async (req, res) => { if (req.code == ...

Dropdown search results bar

$ (function() { var avengers = [ "Black Widow", "Captain America", "Iron Man", "Thor", "Hulk", "Scarlet Witch" ]; document.getElementById('searchBar').onkeyup = searchDropDown; function searchDropDown(){ var input = document ...

Tips for monitoring events emitted through $scope.$broadcast

Help needed with angular-timer events tracking. Specifically, I am unsure how to monitor and respond to events such as when the timer is up. Even after trying to log events to the console, there seems to be no output. vm.add20Seconds = function() { ...

Utilizing JavaScript to fetch and render JSON data, implement a group sorting method to optimize data

I have some JSON data stored in a multi-dimensional array: My goal is to retrieve the top 5 apdex scores by host and display them in a specific format similar to this: So far, I've managed to find the top 5 apdex scores and sort them in descending o ...

JavaScript opacity adjustments not achieving desired outcome

My attempt to make this sub menu fade in and out upon button press is not working as expected. It should fully fade in shortly after clicking 'help' and completely fade out when clicking 'back'. Is the problem with the method I'm u ...

Continuously receiving the value of undefined

I am currently working on a JavaScript Backbone project and I have declared a global object as follows: window.App = { Vent: _.extend({}, Backbone.Events) } In the initialize function, I have done the following: initialize: function () { window.App ...

The absence of a property map within String Flowtype has caused an issue

There is an issue with Flowtype when it comes to arrays. type Properties = { films?: Array<any> } render() { const { movies } = this.props; return ( <React.Fragment> <main className="moviedata-container"> { ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...

Typescript raises an issue regarding a React component's optional prop potentially being undefined

I have a basic React component that looks like this: interface ComponentProperties { onClick?: () => void; } const CustomComponent = (properties: ComponentProperties) => { if (!properties.onClick) { return <></>; } ...

Sending a reference to the event object within a JavaScript function

There are times when we need to use the event object in JavaScript. Below is an example of how we can pass the event: function test(e){ console.log(e); e.preventDefault(); console.log("You are not going to redirect"); } HTML <a href="www. ...

Reliable selection menu for changing fields

Can someone help me with this coding issue? I am attempting to create a dependent dropdown menu where selecting a category will also display relevant equipment. However, in my current setup, only the category field is functioning properly. When I try to a ...