Modifying a data point using various inputs in AngularJS

In this scenario, my goal is to create a system where a remaining amount decreases as the user inputs values into a series of text fields.

Using an angular loop to generate these text fields, I need to update the "remainingAmount" variable accordingly. For instance, if the initial remaining amount is 40 and the user enters 10 into the first field, the remaining amount should decrease to 30, continuing until it reaches 0.


    <div class="row">
            <div class="col text-center error">
                <span ng-model="remainingAmount">{{ remainingAmount }}</span> left to distribute
            </div>
        </div>
    </div>

    <div class="list">

        <div class="item item-button-right" ng-repeat="user in users">
            {{ user.first_name }} {{ user.last_name }}
            <span class="item-note">
                <input type="text"  />
            </span>
        </div>

    </div>

Plunk: http://plnkr.co/edit/NmwTfGNC7jJyRL1kADCJ

Answer №1

To efficiently manage your inputs, consider binding them to your model. This way, you can easily calculate the remaining amount whenever there is a change in one of the inputs:

HTML:

<input type="text" ng-model="user.amount" ng-change="calc()" />

JS:

$scope.calc = function() {
  var total = 0, user;
  for (user in $scope.users) {
    total += parseInt($scope.users[user].amount, 10) || 0;
  }
  $scope.remainingAmount = Math.max($scope.startAmount - total, 0);
} 

Take a look at the example on Plunker

Answer №2

Here is a straightforward example with no validation or additional features. I noticed that an object was being used as an array, so I made a switch to using an actual array. Additionally, I changed the input from text to number in order to prevent the need for re-parsing the number since Angular automatically sets the property as a string:

Link to plunker demo

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
    var maxAmount = 40;
    $scope.remainingAmount = maxAmount;
    $scope.users = [
        {'id':1, 'first_name':'Joe', 'last_name': 'Bloggs', amountUsed: 0},
        {'id':2, 'first_name':'Chris', 'last_name': 'Scott', amountUsed: 0}
    ];

    $scope.updateUsage = function(){
      var totalUsed = 0;

      for (var i = 0; i < $scope.users.length; i++) {
        var u = $scope.users[i];
        totalUsed += u.amountUsed;
      }

      $scope.remainingAmount = maxAmount - totalUsed;
    }
});

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

What is the best way to design an angular directive or service specifically for straightforward pagination featuring only next and previous options?

Within a block of div tags, an ng-repeat directive is being used to display sets of 3 divs at a time. By clicking on the next button, the next set of 3 divs should be displayed, and the same goes for the previous button. Check out the HTML code below: &l ...

Is there a way to implement a targeted hover effect in Vue Js?

I'd like to create a hover button that only affects the nested elements inside it. Right now, when I hover over one button, all the nested elements inside its sibling buttons get styled. Any ideas on how to fix this? <div id="app"> <butto ...

Utilizing square brackets in Node.js for working with URLs

While working in express.js, I encountered an issue when trying to add a router for the URL /xxx/xxx/items[5] that contains square brackets. The router functions correctly without square brackets but fails to work when they are included in the URL. Has a ...

Tips for effectively refining an Angular model (array) without compromising its integrity

I am currently working with a model for my view. This model consists of an array of objects: var arr = { "12345qwery": { prop1: "value", prop2: "value" } } // consisting of 500 items When filtering this array today, I use the following method: arr = $ ...

The intricacies of AngularJS table headers

I am in the process of developing a Timesheet application. The layout (html/css) is already prepared, and I am currently focusing on the behavior of the layout. My main objective at the moment is to extract the timesheet table header into a directive. The ...

What is the best way to change an object into an array using JavaScript?

When retrieving data from Firebase, I encountered an issue where I needed to convert the object into an array. Despite trying to use a foreach loop with map, I was unable to successfully achieve this conversion and ended up with an array of length 0. 0: { ...

Unable to retrieve the form from the website

My goal is to extract the login form from: Although I can see the form element when inspecting in Chrome, I'm encountering difficulties retrieving it using the jaunt API in Java. userAgent = new UserAgent(); userAgent.visit("https://etoro.com/login" ...

The contents of the div disappear when using jQuery to extract it from a string

Update: I finally uncovered the reason behind the empty content of the #output div. The content is fetched from the server, which takes some time; by the time the document loads, the div remains empty. Does anyone have suggestions on how to extract infor ...

Exploring Unicode in JavaScript to iterate through emojis with different skin tones

Currently, I am facing an issue where Javascript splits emojis with different skin colors into multiple characters instead of treating them as one. Emojis with a yellow skin color work fine and give me the desired results. For example: let emojis = [..." ...

Encountered an AngularJS error: [$injector:modulerr] issue following the implementation of gulp-concat

My Angular app functions properly when I manually load all the scripts, but encounters issues when I attempt to use gulp-concat to consolidate them into a single bundle.js file. Currently, I am loading AngularJS and jQuery from a CDN before the other scri ...

"Encountering issues when trying to POST data from an Ember component to an

When attempting to post from a component in my Ember app to my Express API, I am encountering the following error: SyntaxError: Unexpected token V in JSON at position 0 Upon inspecting the response in the network inspector on Chrome, I found this error m ...

"Troubleshooting: Author information not appearing in posts (AngularJS, $http, MongoDB) - Comprehensive guide on MEAN Stack

I recently started learning MEAN Stack Web Development and have been following the tutorial at mean-stack-tutorial. I reached the section on authenticating users, and everything seems to be working well with no console errors. However, in my MainCtrl withi ...

Tips for creating a nested div structure using JavaScript

I am facing an issue with my results object that includes data like Creation_date and approval_date. I have put the results in a loop in JavaScript and created nested divs. However, when I debug it, the divs are not nested as expected. Each one seems to ...

Button with CSS accordion menu

Seeking assistance as I am new to web design and experiencing an issue with my accordion button. I am trying to implement an animation that will display my <ul> when clicking within the .container element. The animation works fine, but I am having tr ...

How to Retrieve Values from a Movie API?

Struggling with The Movie Database API integration. Specifically, I'm stuck on retrieving the "keys" variable when calling the function with the Movie's id. I'm still learning JavaScript, so this is proving to be a bit challenging. Any assis ...

The operation has stopped with error code 1 due to an unhandled error. The error message states: "Unauthorized access for user ''@'localhost' (without password) in express js."

After numerous attempts at debugging, the error persists. However, when I don't debug, everything seems to work fine. I've tried all the solutions I could find, but nothing seems to be working. Any suggestions would be greatly appreciated. The ...

animating an SVG box using JavaScript

Here is an interactive SVG box that can be moved using arrow keys. I am looking for a way to make the box stop moving when the arrow keys are released, and continue moving in the direction of the key pressed. This application utilizes SVG, JavaScript, an ...

Click on the paint app to change colors using JavaScript

Trying to create a Paint feature in JS, here's the code snippet. I am looking to change the color of the trail from black to red by clicking on the "red" div, but I'm running out of ideas (without jQuery). let active = false; const draw = fu ...

Is a streamlined jQuery version of the Slider control designed specifically for mobile devices on the horizon?

Currently, I am developing a mobile web app and would like to incorporate the JQuery Slider control. http://docs.jquery.com/UI/Slider However, in order to do so, it seems that the entire JQuery core (29kb compressed & gzipped) is needed. My question ...

Inserting information into an array: Access the final index consistently with TypeScript

I am interested in dynamically creating a table by allocating it, with the variable nbrBoules: boules:Boule :[] boule:Boule; Boule{id,poids} Method(){ for (var _i = 0; _i < this.nbrBoules; _i++) { this.boule.id = _i; alert(_i); this ...