Real-time changes may not be instantly reflected in the model update

I need to add two numbers together and display the sum in a third input field:

HTML

<div ng-app="myApp">
  <div ng-controller="MainCtrl as mainCtrl">
    Main {{mainCtrl.foo}} <br/>
    <input type="text" ng-model="mainCtrl.foo"/>
    <input type="text" ng-model="mainCtrl.foo2"/>
    <input type="text" ng-model="mainCtrl.foo3"/>
    <br/>
  </div>
</div>

JS

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

var my = {};

my.MainCtrl = function() {
  this.foo = '1';
  this.foo2 = '2'
  this.foo3 = this.calculateSum();
}

my.MainCtrl.prototype.calculateSum = function() {
  return this.foo + this.foo2;
}

// registering all controllers
myApp.controller('MainCtrl', my.MainCtrl);

I am facing the issue that the third input field is only updated on initial load and does not change dynamically while I am typing values in the first two inputs.

Fiddle: http://jsfiddle.net/K64wb/

Answer №1

Implement the ng-change parameter for input-fields 1 and 2. Here's a solution just for you ;) ng-change="mainCtrl.foo3=mainCtrl.sumUp()" For instance:

<div ng-controller="MainCtrl as mainCtrl">
    Main {{mainCtrl.foo}} <br/>
    <input type="text" ng-change="mainCtrl.foo3=mainCtrl.sumUp()" ng-model="mainCtrl.foo"/>
    <input type="text" ng-change="mainCtrl.foo3=mainCtrl.sumUp()" ng-model="mainCtrl.foo2"/>
    <input type="text" ng-model="mainCtrl.foo3"/>
    <br/>
</div>

Answer №2

Upon loading your view, the controller function is triggered only once. It assigns values to foo and foo2, computes foo3, and completes its operation. this.sumUp will not be invoked again.

One suggestion provided by Mularski is to add

ng-change="mainCtrl.foo3=mainCtrl.sumUp()"
to the input boxes. This will ensure that the sumUp function is executed and its result is assigned to foo3 every time the input value is modified. However, this approach may seem cluttered, especially if more input boxes are to be added for summation.

Alternatively, you can directly assign the sumUp function to foo3 like this

this.foo3 = this.sumUp;

Instead of assigning the result of sumUp as you are currently doing (this.foo3 = this.sumUp();). Then, in your view, set foo3() as the ng-value of the textbox:

<input type="text" ng-value="mainCtrl.foo3()"/>

(Note that it cannot be assigned to ng-model as the function is not writable).

By instructing the textbox to always display the result of that function, it will automatically update whenever any of its dependencies change (such as foo and foo2).

Here is a Fiddle for reference.

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

Include the array in the 'content' property of the CSS using Jquery

I need help formatting data in CSS. The code I have is as follows: if (ext){ switch (ext.toLowerCase()) { case 'doc': pos = 'doc'; break; case 'bmp': pos = 'bmp'; break; ...

Deleting a record in MongoDB based on a specific value present in a column

I am in search of more information about delete triggers in MongoDB. Source: Query on MongoDB Delete Triggers I am interested in converting DELETE operations to UPDATE + AUTOMATIC DELETE. To achieve this, I plan to introduce a new field called "flag" ...

Building a matrix-esque table using d3.js reminiscent of HTML tables

I would like to generate a table resembling a matrix without numerical values. 1. Here is an example of my database table: | CODE | STIL | SUBSTIL | PRODUS | |------|-------|----------|---------| | R | stil1 | substil1 | produs1 | | R | stil1 | s ...

Experiencing a problem with the localhost connection

I've been trying to work on this issue using React and local host, but it keeps showing the direct file instead of the website. I've been stuck on this problem for the past 3-4 hours and still haven't been able to find a solution. I'm h ...

Setting the base URL in Next.js according to an environment variable: a step-by-step guide

I currently have a Strapi backend and Next.js frontend application deployed on DigitalOcean. Within DigitalOcean, I have configured an environment variable for the frontend: API_URL = ${APP_URL}/api To generate the base URL, I retrieve this variable using ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

Preserving the Selected Date on the Calendar Even After the PHP Variable is Passed

I am currently using the calendar code below with a slight modification that I implemented. However, I have encountered an issue where when I select a date, the calendar successfully highlights the selected date. But once I pass this selected date along ...

Having issues initializing jQuery knob on a jQuery mobile webpage

I'm trying to implement the jquery knob plugin to showcase a circular rating system, but I'm encountering difficulties in getting it to display properly. Below is the code snippet I'm using - can someone please point out what's causing ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Substitute the value in the object associated with a mystery key with a different value from the second object

I am dealing with the following objects: http ={" xxx": "#phone#","yyy": "1234", "zzz":5678 } input= {"phone": "2", "id": "258 }, Can someone help me find the #phone# val ...

Assign Attribute to a Different Data Transfer Object

I have a query regarding my nestjs project - is it possible to assign a value Attribute to another Dto? Specifically, I'm looking to assign idData to the id in IsUniqueValidator. I attempted the following code but it resulted in 'undefined&apos ...

Mapping over an array and ignoring any undefined properties in a dynamic object

Looking for a way to dynamically create objects in the 'map' function to reduce the final array size. The goal is to avoid adding properties with undefined values. For example, if 'offst: undefined', skip this property but add others wi ...

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

Having trouble storing data in a database with PHP in an AngularJS application

<!DOCTYPE html> <html ng-controller="controller" ng-app="app"> username:<input type="text" placeholder="*username" ng-model="user"><br><BR> password:<input type="password" placeholder="*password" ng-model="pass" &g ...

Passing default props to a component in React that includes a function as one of the

I am working on a React component that has default props set. The issue arises when I try to pass an additional prop, specifically a function. class MyComponent extends Component { constructor(props) { console.log('props', props); supe ...

Arranging arrangements in javascript

I am dealing with objects that contain the fields id and position. const items = [{id: 11, position: 1}, {id: 12, position: 2}, {id: 13, position: 3}, {id: 14, position: 4}, {id: 15, position: 5}, {id: 16, position: 6}]; These objects represent folders st ...

How can I save the content from a tiptap editor in a PHP form?

I'm looking to integrate the TipTap editor into a PHP form as a textarea field. I've set up a Vue component and passed it to the blade view. Blade view: <form method="post" action="{{ route('dashboard.edit.postInfo', ...

Escape key does not close the modal dialogue box

I’ve customized the codrops slide & push menu (http://tympanus.net/codrops/2013/04/17/slide-and-push-menus/) to create an overlay on a webpage. Although it functions as intended, I’m struggling to implement a way to close it by pressing the escape ...

Because of the CSS tree structure, it is not possible to add or remove classes. This restriction applies to all actions done in jQuery, including click

I want to create a hover effect where the CSS changes when hovering over an item, then reverts back to normal when no longer hovered. Additionally, I would like the CSS to change when the item is selected, and return to normal when another item in the same ...

Change the class name using jQuery when scrolling

Currently utilizing bootstrap as my primary css framework. My goal is to dynamically toggle a class on the navbar once the user scrolls past the prominent header image located at the top of the website. UPDATE: Admitting I made an error and had a momenta ...