John Kevin M. Basco John Kevin M. Basco - 5 months ago 13
AngularJS Question

How to automatically set the value of an input box to the opposite number when there's an input in any of two input boxes?

Let's say we have 2 input boxes:


  1. num1

  2. num2



When the user inputs a number in any of the 2 input boxes, what we want to happen is automatically set the value of the other input box to the opposite sign of the number.

Examples:


  • User inputs 1 in num1. The value of num2 should automatically be set
    to -1.

  • User inputs -1 in num1. The value of num2 should automatically be set
    to 1.



How can we achieve this when using AngularJS 1.x?

Answer

There are a couple ways to do this:

  1. In your controller put a watch on the values of num1 and num2. It might look something like this (assume $scope is injected in your controller)

Example HTML

<input type="number" ng-model="num1">
<input type="number" ng-model="num2">

Example JS

$scope.$watch('num1', function(newVal){
  $scope.num2 = - newVal;
}

$scope.$watch('num2', function(newVal){
  $scope.num1 = - newVal;
}

This way is preferable if you intend to reuse the controller with several views or there is an inherent relationships between the model data (num1 and num2)

  1. In on your input have an ng-change set the value in an angular expression

Example HTML

<input type="number" ng-model="num1" ng-change="num2=-num1">
<input type="number" ng-model="num2" ng-change="num1=-num2">

This way is preferable if you only are only care about one number, or this logic only belongs in the view (as Manatax points out in comments this might more closely match your question)