Is there a more efficient way to manage interactions between multiple controls on a form than using $scope.$watch? This cleaner approach

Currently, I am creating an Angular application that includes a form with approximately 15 controls for a finance-related application. I would appreciate advice on how to improve the structure without suggesting a complete page overhaul.

Several of the controls are interdependent. Five input controls act as sources and can impact five other controls that serve as destinations. To handle this, I have implemented $scope.$watch on each source variable and included specific logic in the watch functions to determine which destination variables need updates. Below is an example of one such watch function:

$scope.$watch('money.price',function(newVal,oldVal) {

    if(newVal != oldVal) {

        if($scope.money.quantity != undefined) {
            updatePrincipal($scope)
            updateFees($scope);
            $scope.money.net = $scope.money.principal + $scope.money.fee 
        }
    }
});

Despite the functionality working, I feel there might be a more elegant solution. Are there any suggestions on how to enhance or streamline this process? (Please keep in mind that the form may become slightly more complex in the future with 2-3 additional dependency fields, but not exceeding that).

Answer ā„–1

If your input controls are linked to an ng-model, it's suggested to include ng-change in each input form. This way, you can streamline the process by using a single function to update all scope bindings simultaneously.

Answer ā„–2

Utilize the built-in $watch functionality of the ng-bind directive.

<div ng-bind="calculateRevenue()"></div>

     OR MORE SIMPLY

{{ calculateRevenue() }}

Avoid manually creating a $watch in your controller by defining the necessary function.

 $scope.calculateRevenue = function() {
     if ($scope.sales.amount != undefined) {
        updateEarnings($scope)
        updateExpenses($scope);
        $scope.revenue.total = $scope.sales.earnings - $scope.expenses.amount 
     };
     return $scope.revenue.total;
 };

With this setup, the $watch created by the ng-bind directive will automatically compute the value of revenue.total and update the DOM as needed during each digest cycle.

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

Utilize jQuery to dynamically update the checklist with stylish elements and display the total number of items in real

I have a list that can sometimes contain 5 elements, other times it may have 7. I want to determine the number of elements and apply a special style to those with less than 5. The current code I have is not working as expected... Perhaps I need to implem ...

Choosing various buttons using jQuery

I'm trying to create a feature where I have a list of items with buttons next to each one. When a button is clicked, I want the corresponding item to be displayed in another section on the page. The challenge Iā€™m facing is figuring out how to estab ...

I am eager to output the JavaScript value

My JavaScript code in a webpage looks like this. <SCRIPT language="javascript"> function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table. ...

Submitting a form in React/Javascript: A step-by-step guide

I have a website on Wordpress where I am using the Wp-Polls plugin to vote. How can I submit a post request by accessing a form URL in a React project? Specifically, how can I vote for the "Bad" option with a value of 2? The HTML structure of the WordPre ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

Drawing a line in THREE JS where the endpoint is a vector not related to the object or its parent

In my scene, I have a hierarchy of objects where one is the parent and the other is the child. My goal is to determine a Vector3 relative to the deepest child object that points towards a specific vector in the scene (look_point). var grandParent = new T ...

The focus on TextField in Material UI + React gets lost when applying styles to a card

Is there a way to style my card so that it appears smaller without affecting the functionality of my TextField? Whenever I try to reduce the size of the Card component, the TextField loses focus and I have to keep clicking on it. How can I make the Card sm ...

Activate the ability to upload files if the check box is checked

How can I ensure that when the show checkbox is true (show = Boolean type), the file upload is enabled by default when the checkbox is not checked? I have tried the following code but it is not functioning properly; the enable/disable feature does not wo ...

On my WordPress Elementor website, I am looking to have the button on my product card linked to a specific

I found a product card design on codepen.io and tried to customize it by changing the colors. However, I'm struggling to get the button to work. Here is the product card code snippet: <div class="card"> <div class="imgBox&q ...

Tips on eliminating the letter 'X' from a text/search input field in HTML

There are various solutions available for removing the "X" from an input field in IE 10+ browsers. I have tried multiple approaches without success. For example, I have referenced: ans 1 ans 2 ans 3 Despite implementing all of these solutions, I still ...

JavaScript Paint Brush Tool Powered by HTML5

I am looking to create a smooth and clean opacity brush. Here is an example of the drawing line I want: This is the second picture I managed to achieve: When I move the cursor quickly, there are fewer circles in the drawing line. ...

AJAX Object Creation: Only Visible After Manual Refresh

Currently, I am in the process of building a basic to-do app that includes multiple different lists, each of which contains a variety of items. My main objective is to integrate AJAX functionality into the creation and display of lists on the lists#index p ...

Classify the JavaScript objects according to the array of object lists

Struggling to find a solution for converting this list of objects based on the group array. The challenge lies in iterating through the group Array and applying the object to multiple places when there are several groups. Additionally, trying to disregard ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Uploading images in React JS by allowing users to paste images

Currently working on a chat application using React JS and I'm looking to enable image uploading when an image is pasted into the chatbox. How can I make this happen? Essentially, I am in need of: An event that will activate upon performing the "Pas ...

At what point does Angular erase the $watch?

As I delve into Angular and add models to my view, I am aware that each one enters the digest loop and has a $watch function applied to it. Since Angular apps are essentially single page applications, this process is crucial for updating data across the ap ...

Trigger the ng-change event for a textbox using a method other than keypress or keydown

Looking to dynamically update a text value without triggering the update method while typing in the textbox. The update method should only be called when exiting the textbox or changing it through script code: <input type="text" ng-model ="model.value" ...

Remove an item from a multidimensional array that contains a specific key-value pair

I need to remove the low-level object (for example, in the code below, under personal data there are two objects, I want to delete the one where action is "OLD") under each section where the "action" is "OLD" I'm utilizing lodash in my current projec ...

The array element is not being shown in the id "main" when using a for loop with the onchange function

I've been using document.write to display specific content, but it seems to be removing other elements from the page. Is there a way for me to display this loop inside the element with id="main" without losing any content? When I attempt to use docume ...

Fetching the Key-Value pairs from a HashMap in JavaScript/AngularJS

I am currently working with a HashMap in the Frontend that is being retrieved from the Backend: var myVar = {"24":{"amount":2,"minutes":30},"32":{"amount":3,"minutes":30}} Can anyone offer guidance on how to access both the keys and values in Javascript ...