Here are a couple of methods to achieve this:
- To start, you can add a watch in your controller for the values of num1 and num2. It would look something like this (assuming $scope is injected into your controller)
Sample HTML
<input type="number" ng-model="num1">
<input type="number" ng-model="num2">
Sample JS
$scope.$watch('num1', function(newVal){
$scope.num2 = -newVal;
}
$scope.$watch('num2', function(newVal){
$scope.num1 = -newVal;
}
This method is recommended if you plan on using the controller with multiple views or if there is a relationship between the model data (num1 and num2). The watches will trigger whenever the numbers change for any reason (other bindings, manual changes in JavaScript, etc).
- Alternatively, you can use ng-change on your input fields to set the value in an angular expression
Sample HTML
<input type="number" ng-model="num1" ng-change="num2=-num1">
<input type="number" ng-model="num2" ng-change="num1=-num2">
This approach is ideal if you only need to focus on one number, or if this logic specifically belongs in the view. It may also be more efficient as it listens for the change event instead of checking for equivalence every digest cycle. However, keep in mind that if either number changes through means other than altering the input field directly, the change will not be reflected. Thanks to Manatax for highlighting most of these benefits in the comments below.