Is it possible for Angular to perform bidirectional data binding in reverse between two input fields?

I'm struggling to get my two input fields to update values when the opposite input is changed.

My goal is to create a simple $dollar to Gold oz calculator with two input fields. You can see a sample preview here: http://embed.plnkr.co/dw6xL95zRqJC1pIlE1Kf/preview

The first input field is for the dollar amount, the second one is for the ounces amount. There is also a third variable that contains the gold selling rate.

In my code, I have managed to successfully change the Dollar amount and update the oz amount using angular's two-way data binding.

The issue arises when trying to make the opposite scenario work; for instance, changing the oz amount should automatically update the dollar amount.

Below is my HTML code:

<div class="row panel" ng-controller="ctrl">

  <!-- Dollar input -->
  <label class="small-6 columns">Dollar $:
    <input type="number" ng-model="dollar">
  </label>

  <!-- Ounces input -->
  <label class="small-6 columns">Ounces (oz):
    <input type="number" value="{{ ozCalc() | number:4 }}">
  </label>

</div>

And here is my AngularJS code:

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

app.controller('ctrl', ['$scope', function($scope) {
    $scope.dollar = 0;
    $scope.oz = 0;
    $scope.rate = 1267;

    //Dollar to Ounce Calculator
    $scope.ozCalc = function() {
        var oz = $scope.dollar / $scope.rate;
        return oz;
    };

    //Ounce to Dollar Calculator
    $scope.dollarCalc = function() {
        var dollar = $scope.oz * $scope.rate;
        return dollar;
    };

}]);

Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

To start, make sure you are implementing 2-way binding for the oz input as well:

<input type="number" ng-model="oz">

Next, set up watches for both models:

$scope.$watch('dollar', function(newVal, oldVal) {
    $scope.oz = calculateOunce(newVal);
});

$scope.$watch('oz', function(newVal, oldVal) {
    $scope.dollar = calculateDollar(newVal);
});

You may want to consider refactoring these functions into a service for better organization:

//Function to convert Dollar to Ounces
function calculateOunce(dollar) {
    var ounces = dollar / $scope.rate;
    return ounces;
}

//Function to convert Ounces to Dollar
function calculateDollar(ounces) {
    var dollar = ounces * $scope.rate;
    return dollar;
}

This approach avoids triggering infinite digest cycles. Check out this updated plunker example for reference: http://plnkr.co/edit/abcd123xyz?p=preview

If you need the oz input to have a 4-digit format, utilize the ngModel.$parsers/$formatters pipelines instead of applying a filter.

Answer №2

To make changes based on user input, consider using ng-change in your HTML code:

<div class="row panel" ng-controller="ctrl">

  <!-- Dollar input -->
  <label class="small-6 columns">Dollar $:
    <input type="number" ng-model="dollar" ng-change="update()">
  </label>

Implement a function in Angular to update the ounces value:

$scope.update = function() {
    // Add logic similar to ozCalc()
    $scope.oz = updatedValue;
}

Ensure you have appropriate expressions for ng-model and ng-change:

  <!-- Ounces input -->
  <label class="small-6 columns">Ounces (oz):
    <input type="number" ng-model="oz" ng-change="update2()">
  </label>

</div>

Add another function in Angular to handle the second update:

$scope.update2 = function() {
    // Implement necessary logic
    $scope.dollar = updatedValue;
}

Remember to follow best practices with ng-model usage:

https://github.com/angular/angular.js/wiki/Understanding-Scopes

Always include a '.' in your ng-models to avoid issues with primitives.

Organize your models properly to ensure smooth operation:

<input type="number" ng-model="amount.oz">

Define your model structure like this:

$scope.amount = {
    oz: 0,
    dollar: 0
}

Avoiding conflicts between parent and child nodes is crucial for correct variable editing, especially in scenarios like ng-repeat.

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

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

Steps for displaying an image link on an aspx webpage

Is it possible to have the full-size image open on http//example.com/image.aspx when the thumbnail is clicked, instead of http//example.com/images/image.jpeg? I am looking for a solution that does not require creating individual pages for each image or edi ...

Is there a way to display a div element just once in AngularJS?

I only want to print the div once and prevent it from printing again. $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', '_blank', 'width=300, ...

Showing data retrieved from nested JSON arrays in React Native

Recently, I delved into the world of React Native and encountered a challenge in displaying nested elements from fetched JSON data. Despite utilizing react hooks in the fetch API, I couldn't quite crack the code. export default function MedProfilScre ...

What are the steps involved in manipulating objects within an asynchronous result object?

I'm interested in learning how to manipulate a JS object from one file into another asynchronously, as my experience with asynchronous code principles is limited. Scenario: In my app.js file, I dynamically generate 'app panels' based on ...

Error message "Unexpected token" occurs when attempting to use JSON.parse on an array generated in PHP

My attempt to AJAX a JSON array is hitting a snag - when I utilize JSON.parse, an error pops up: Uncaught SyntaxError: Unexpected token Take a look at my PHP snippet: $infoJson = array('info' => array()); while($row = mysqli_fetch_array($que ...

Incorporate an icon into an Angular Material input field

I want to enhance my input search bar by adding a search icon from Angular Material : <aside class="main-sidebar"> <section class="sidebar control-sidebar-dark" id="leftMenu"> <div> <md-tabs md-center-tabs id=" ...

sending a string of JSON in PHP (including quotes) to an onclick event function

I am faced with the challenge of passing an array of data from PHP to JavaScript for the "onclick" event. The approach I took was to convert the array data into a JSON string which could then be parsed back in the JavaScript function for manipulation. How ...

What are some ways to restrict dynamic form submissions?

$(document).ready(function(){ var i = 1; $('#add').click(function(){ if(i < 5){ i++; $('#dynamic_field').append('<tr id="row'+i+'"><td><div class="form-group">& ...

The start screen fails to display when clicking the restart button

I am struggling to get the restart button to display the start screen again. Even though I have called the restart function within the clearColors function, which should show the start screen, it hasn't been effective so far. Initially, in the fadeOut ...

Issues with selecting elements in AngularJS using CasperJS

I have attempted all solutions provided in the following link: How to fill a select element which is not embedded in a form with CasperJS? , as well as explored many other sources. The issue I am facing is that I am unable to modify the code below to inclu ...

Adding information to a single class that shares a common name

Currently, I have successfully implemented a row cloning scenario where multiple dynamic rows are created after confirming an inventory number from a MySQL database. However, I am facing an issue with inserting the inventory data only to the next DIV eleme ...

PHP regular expression /only match 10 whole digits/;

Currently, I am working on updating a PHP script that contains the following code snippet: function CheckNumber(MyNumber) { var MN = /^\d{10}$/; if (MN.test(MyNumber)) { return true; } return false; } The current script enfor ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

A JavaScript regex that can identify white spaces and new lines to calculate word count

Currently, I am attempting to count words within the Summernote editor using Angular. While I have successfully created a service for counting words, it seems to be ineffective when encountering new lines. Here is an example of the text: Hult Internation ...

What is the best way to limit dates on an angular-datepicker?

I'm having trouble setting the maximum and minimum date in angular-datepicker. For more information, you can visit the angular-datepicker link. <div date-picker="start" min-date="Date string | Expression" max- date="Date string | Expression">&l ...

Error message: Uncaught TypeError - Unable to access property value from null reference in Quicksort.js

Can someone assist me in resolving the "uncaught typeerror cannot read property of null" issue I'm facing on line 4 of my JavaScript code? This is my first post on this platform and I hope to find some help here! function sort() { var array = docume ...

How to retrieve the value of a table row by clicking with the mouse using jQuery?

I am having an issue with my table data display. Each row in the table is assigned a unique ID, which corresponds to the value of the tr-tag. My goal is to log this ID in the console when a table row is clicked. Here is the table: $.getJSON(`http://local ...

Changing color based on AngularJS condition using CSS

My HTML code looks like this: <div> <i class="glyphicon glyphicon-envelope" style="margin-top: -50px; cursor:pointer; color: #1F45FC" ng-click="createComment(set_id)"> </i> Route <center> ...

Is it possible to apply JavaScript object destructuring but make changes to certain values before assigning them to a new object?

After receiving movie data from an api, I am currently manually creating a new object with a subset of properties and modified values. Is there a more efficient way to achieve this using javascript/typescript object destructuring syntax? I specifically wa ...