What is the best way to connect three or more variables with one-to-one relationships in AngularJS?

Let's say I want to create a unit converter using AngularJS. I also want the ability for multiple values to change simultaneously when editing.

What I mean is, if we have 3 variables, then when one changes, the other two should automatically update.

Is this achievable?

Here is a snippet that demonstrates 3 units of distance - petameters, light years, and parsecs:

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

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

myControllers
  .controller('MyController', ['$scope', function ($scope) {
    $scope.petameters = 10;
    $scope.lightyears = $scope.petameters / 9.460730472580800;
    $scope.parsecs = $scope.lightyears / 3.2616;
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
    <div ng-controller="MyController">
      Petameters:<input type="text" ng-model="petameters"><br/>
          Light years:<input type="text" ng-model="lightyears"><br/>
          Parsecs:<input type="text" ng-model="parsecs"><br/>
    </div>
</body>

How can I get this code to function correctly?

UPDATE

Below is the refined code:

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

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

myControllers
  .controller('MyController', ['$scope', function ($scope) {
    
    $scope.petametersChanged = function() {
    $scope.lightyears = $scope.petameters / 9.460730472580800;
    $scope.parsecs = $scope.lightyears / 3.2616;
    }
    
    $scope.lightyearsChanged = function() {
    $scope.petameters = $scope.lightyears * 9.460730472580800;
    $scope.parsecs = $scope.lightyears / 3.2616;
    }
    
    $scope.parsecsChanged = function() {
    $scope.lightyears = $scope.parsecs * 3.2616;
      $scope.petameters = $scope.lightyears * 9.460730472580800;
    }
    
    $scope.petameters = 10;
    $scope.petametersChanged();
    
  }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
    <div ng-controller="MyController">
      Petameters:<input type="text" ng-model="petameters" ng-change="petametersChanged()"><br/>
          Light years:<input type="text" ng-model="lightyears" ng-change="lightyearsChanged()"><br/>
          Parsecs:<input type="text" ng-model="parsecs" ng-change="parsecsChanged()"><br/>
    </div>
</body>

Answer №1

Give this a shot:

JavaScript

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

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

myControllers
  .controller('MyController', ['$scope',
    function($scope) {
      $scope.petameters;
      $scope.lightyears;
      $scope.parsecs;

      $scope.update = function(unit) {
        console.log('In Update');
        if(unit === 1) {
          $scope.lightyears = $scope.petameters / 9.460730472580800;
          $scope.parsecs = $scope.lightyears / 3.2616;
        } else if(unit === 2) {
          $scope.petameters = $scope.lightyears * 9.460730472580800;
          $scope.parsecs = $scope.lightyears / 3.2616;
        } else {
          $scope.lightyears = $scope.parsecs * 3.2616;
          $scope.petameters = $scope.lightyears * 9.460730472580800;
        }
      };
    }
  ]);

HTML

<body ng-app="myApp">
  <div ng-controller="MyController">
    Petameters:
    <input type="text" ng-model="petameters" ng-keyup="update(1)" />
    <br/>Light years:
    <input type="text" ng-model="lightyears" ng-keyup="update(2)" />
    <br/>Parsecs:
    <input type="text" ng-model="parsecs" ng-keyup="update(3)" />
    <br/>
  </div>
</body>

Check out the Plunker demo

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

Trick your way into generating a faux 504 error on a node-express server

I have recently made changes to my code that now retries a request when error 504 occurs (only once). However, I am looking for ways to test this functionality by faking an error. Can someone provide guidance on how to do this? (The server is using Node Ex ...

A fusion of Angulary and Django REST

What is the best way to filter my queryset? For instance: .controller('TViewController', ["$scope", "$stateParams", "Ad", "Banner", function($scope, $stateParams, Ad, Banner) { $scope.ad = Ad.get({ ad_id: $stateParams.ad_id }); $scope.b ...

Sudden slowdown due to Jquery error

I am encountering an issue with the Jquery registration validation. I am struggling to display the error message if a name is not filled in. jQuery(document).ready(function () { $('#register').submit(function () { var action = $(thi ...

What is the process to unregister a service worker from Django login and admin pages?

I utilized Django to create an application and integrated the service worker into it. However, I encountered an issue when navigating to the login and admin pages as I needed to disable the service worker in those specific areas. Learn more about Service ...

What sets xhr.response apart from xhr.responseText in XMLHttpRequest?

Is there any difference between the values returned by xhr.response and xhr.responseText in a 'GET' request? ...

PageCallbacks in .NET 1.1

Is it possible to utilize PageMethods in .NET 1.1 for making server-side method calls from the client side? Could you provide a brief explanation on how to use this feature by calling PageMethods.MyMethod(); ? ...

Tips for adding a console.log statement to material-ui components to confirm the object/array/value

An issue arises in my React JS code snippet execution that I need help with: <TableBody> { (data.length > 0) ? ( data.map((x, i) => row( x, i, formColumns, handleRemove, handleSelect, editIdx ))) : (<TableRo ...

Issue with AngularJS AJAX Request

When working with AJAX calls, how can we improve error handling to make it more meaningful? Using the template code provided may not effectively communicate the issue. What are some ways we can better understand and handle exceptions? <script> ...

Is server-side pagination only possible if the server supports it? Are there any APIs that specifically cater to pagination needs?

I need some guidance on implementing pagination in my "angularJs" application. Currently, I have a dropdown menu that utilizes the angular-ui framework. My goal is to have the application load the initial set of data from an "API" upon launch, and then r ...

What is the best way to access a nested promise element in Protractor?

I've recently put together a function in protractor that I'd like to share: function findChildElementByText(parentElement, tagName, textToSearch) { return parentElement.all(by.tagName(tagName)) .then((items) => { items.map( item ...

Encountering an issue with an Uncaught SyntaxError: Unexpected identifier

I've been attempting to send data through ajax but keep encountering errors. Here's the code I have: jQuery.ajax({ url : '', type: 'POST', ...

Highlighting syntax on the server side

I have some code blocks that I want to emphasize. Currently, I am using prismjs for this purpose. However, when I try to highlight several code blocks, the page takes more than 5 seconds to load on my somewhat slow PC. Interestingly, if I remove the prism ...

Error: The locator I used with the ID getUserById did not find any elements

Here is the code snippet from my HTML file: <h1>User list</h1> <button class="btn btn-primary" [routerLink]="'/register'">Register</button> <br> <br> <table class="table& ...

Do you want to proceed by clicking on the download link and closing the

I recently acquired a GUI built with Angular, and I'm struggling to simplify it to a basic example. I'm hoping for a straightforward solution that isn't too complicated. There's a modal dialog using Bootstrap that's similar to the ...

Guide on converting AS3 to HTML5 while incorporating external AS filesAlternatively: Steps for transforming AS

I've been given the challenging task of transforming a large and complex Flash project into html5 and javaScript. The main stumbling block I'm facing is its heavy reliance on external .as files, leaving me uncertain about the best approach. Most ...

Learn how to display a "not found" message in a React.js application

I have a piece of code where I am sending a post request to an API and retrieving all the data from the API in a table. I am trying to find currency data based on the currency name, if found I display the data in a div, if not found I want to print "not ...

Verify if the link includes https:// while using angularjs

In my angular app, there is a lot of data stored in JSON format. [ {"link": "https://stackoverflow.com"}, {"link": "https://stackoverflow.com"}, {"link": "id-aW783D"}, //This data is incorrect {"link": "https://stackoverflow.com"} ] However, the ...

The particles from particles.js plugin fail to appear on Chrome browser

While experimenting with particles.js, I noticed that it runs smoothly on the Safari browser (I'm using a MacBook), but it encounters an error on Chrome and the particles fail to display. Error pJS - XMLHttpRequest status: 404 particles.js:1558 Error ...

Validate if the Jquery AJAX response contains any data

I've been attempting to integrate an alert message in my code that triggers if the response is null, but every time I try to do so, something goes wrong. If anyone has any suggestions or assistance with this issue, it would be greatly appreciated. He ...

When updating the location.hash property via a click event, it appears to be set to

Check out the code snippet below: $(e).click(function() { console.log(this.href); location.hash = this.href; }); In this code snippet, e refers to a <li> element structured like this: <li href="#about">About</li> The location. ...