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>