Saving the output of an AngularJS expression in an input field

Looking at the calculations below, I am currently evaluating an expression, {{ annualIncome * 4.5 }}, in one input and then re-evaluating the same expression in another input. Instead of saving the result and transferring it to the other input, I am repeating the calculation as I am unsure how to proceed.

For Example:

%label Equity Loan ({{ selectedLocation.loan }}%):
%input#equity_loan{ "disabled" => "disabled", "value" => "{{ selectedLocation.mortgage === 55 ? ((annualIncome * 4.5) / 11) * 9 : ((annualIncome * 4.5) / 15) * 4 }}" }

%label Mortgage ({{ selectedLocation.mortgage }}%):
%input#mortgage{ "disabled" => "disabled", "value" => "{{  annualIncome * 4.5 }}" }

I attempted to use ng-model but encountered difficulties making it work.

I also tried converting the values to currency by adding "| currency" at the end of my expression, which did not yield the desired outcome. I suspect this may be due to the need to convert each result individually

Answer №1

While you cannot directly use variables in angular expressions, you can manipulate them in your controller once a specific variable, like annual income, is updated. This variable is typically linked to your view using the "ng-model" => "annualIncome" statement.

To recalculate values after a change, you can create a watch in your scope that triggers a function whenever the value is modified. If you prefer to add a delay before recalculating, you can utilize the debounce options available in ng-model-options. For example:

%input{"ng-model-options" => "{debounce: { 'default': 500, 'blur': 0 }}"}

This approach allows for better structuring by manipulating variables within your code.

$scope.$watch('annualIncome', function(value, oldValue) {
  var annualIncome = value; // equivalent to $scope.annualIncome
  var parts = selectedLocation.mortgage === 55 ? 11 : 15;
  var factor = selectedLocation.mortgage === 55 ? 9 : 4;
  var annualValue = annualIncome * 4.5;
  $scope.result = {
    propertyValue: annualValue + (annualValue / parts) + ((annualValue / parts) * factor),
    deposit: annualValue / parts
    // and more..
  };
});

With the result variable stored on the scope, you can bind it to your view using property binding.

%input#property_value{ "disabled" => "disabled", "value" => "{{ result.propertyValue }}" }

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

Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {} function log(arg: number) { console.log(arg); } function fn<T extends typeof Base>( instance: Partial<InstanceType<T>>, key: keyof InstanceType<T>, ) { const val = instance[key]; if (val) { ...

What is the best way to manage a JSON feed that does not provide any results?

Excuse my lack of experience as I pose my first question. Using FullCalendar 5.10.1, I am working on retrieving events dynamically associated with Festivals. I have followed the 'events (as a json feed)' pattern from the documentation. When ther ...

Utilizing a Node.js web server in conjunction with an Apache Cordova Application

I have created an innovative Apache Cordova Application that leverages a Node.js web server to retrieve data from a web API, enabling the JavaScript-based project to utilize the information obtained from the API. Is there a method to integrate this Node w ...

Issue with preventDefault not functioning correctly within a Bootstrap popover when trying to submit a

I am facing an issue with a bootstrap popover element containing a form. Even though I use preventDefault() when the form is submitted, it does not actually prevent the submit action. Interestingly, when I replace the popover with a modal, the functional ...

Encountered an issue while loading a pretrained JSON model in a JavaScript script within a locally hosted

At the moment, I am using TensorFlow in Python to train a model and saving it as model.json along with the BIN file in a folder named models. My goal is to develop a web application that can load this pre-trained model for prediction. However, I have been ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

Sending Three.js meshes to a web worker through JavaScript

I have a collection of objects, which are meshes generated using Three.js, that I need to perform operations on within a web worker. My question is, how can I send these objects to the worker? My understanding is that there's a concept called transfe ...

Obtaining solely the words found within HTML documents

In my Python 2.7 project, I have a folder containing multiple HTML pages that I need to extract only words from. My current process involves opening the HTML file, using the Beautiful Soup library to extract text, and then writing it to a new file. However ...

"The orderBy function in AngularJS seems to be overlooked or not functioning properly within the

It seems like the orderBy function is being ignored in my code. Despite adding a console.log for testing purposes, the function doesn't appear to be called at all. As a result, the data is still displayed but remains unordered. Snippet of HTML Code ...

Encountering issues with jQuery AJAX POST request

I'm currently facing an issue while attempting to send a post request to parse JSON formatted data into my webpage. Here's an example of the query: $("#click").click(function () { $.ajax({ type: "POST", url: "http://ut-pc-236 ...

Invoke OnSelectedIndexChanged from GridView prior to any other function execution

In my scenario, there are two GridViews available. The first GridView allows the user to select a row, based on which a corresponding list will be displayed according to the selected GridView ID. First Grid: https://i.stack.imgur.com/d0OKq.png Second Gri ...

Encountering a strange issue when attempting to link app.js with mongodb

I recently set up MongoDB and the Compass, everything was working fine until I tried to connect MongoDB with my app.js. Now I'm getting a strange error message. Could anyone help me understand what this error means and how I can fix it? Unfortunately, ...

What is the reason behind the blocking of Ajax GET requests without CORS, while JSONP requests are permitted?

Accessing any page on the web through a GET request using HTML tags from a different origin is possible: <script src="http://example.com/user/post?txt=sample"></script> XHR requests to other origins are blocked for security reasons. For examp ...

Using Angular's ng-repeat prefilter with JavaScript

Is it possible to achieve the functionality of this angular js filter ng-repeat on a tr element using pure javascript? Could it be done in just one custom filter? Please note that showRow is a function that returns a boolean value, and searchString is a s ...

What might be causing Flex not to function properly on my personalized landing page?

I attempted to create a basic landing page featuring an image background with a logo, button, and a row of 4 images displayed side by side using Flex. However, for some reason, the Flex is not functioning properly for the row of images. Here is the code s ...

A recursive function enhanced with a timeout mechanism to avoid exceeding the stack call limit

Trying to search for images on any object of various depths using a recursive function can lead to a Maximum call stack size exceeded error in certain cases. A suggested solution here involves wrapping the recursive function in a setTimeout, but this seems ...

issue with splice function

I have a JavaScript function that is supposed to collect all input values from text boxes and store them in an array. However, I want to remove any input value with the type "button" from the array before proceeding. Here is the code snippet: <!-- lang ...

How can I load data into Vuex store before the application starts?

Within the created hook of App.vue, I am initiating a dispatch call to my store. Subsequently, in a child component, I attempt to retrieve this data using a getter. However, an issue arises as the child component is loaded before the data is stored, causin ...

What could be causing the ng-repeat to remove the incorrect item when splicing?

I'm encountering an issue while trying to splice out items in this ng-repeat based on their $index. Although it works perfectly for adding items, when attempting to delete an item using the same code, it ends up removing only the last item of the arra ...

Techniques for utilizing ng-class to merge class attributes

I'm new to Angular and I want to combine classes using ng-class. Specifically, I'd like to use the save class along with the firstClass class if something = First. I've been doing some research on how to implement this with ng-class but I ha ...