Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing an infinite loop with two $watches

I'm looking for a technique to prevent an infinite loop when using two $watch statements in angular. The idea is when var1 changes, I want it to modify var2. When var2 changes, I want it to modify var1. But that will normally create an infinite loop. Is there a way around this? Below is a trivial example that demonstrates the issue. This code would go in an angular controller.

$scope.$watch('var1', function(newVal){
    $scope.var2 = newVal
})
$scope.$watch('var2', function(newVal){
    $scope.var1 = newVal
})
like image 493
J-bob Avatar asked Dec 03 '25 11:12

J-bob


1 Answers

It actually wouldn't cause an infinite loop since the watch would stop being fired once both vars are equal.

  1. Var 1 is modified by user
  2. Var 1 watch fires and sets var2 = var1;
  3. Var 2 watch fires and sets var1 = var2;
  4. Since var 1's didn't actually change, the watch is no longer fired, no infinite loop happens.

Here's a snippet demonstrating this:

angular.module('myApp', [])
  .controller('myController', function($scope) {

    $scope.$watch('var1', function(newVal) {
      $scope.var2 = newVal;
    });

    $scope.$watch('var2', function(newVal) {
      $scope.var1 = newVal;
    });

  });
<!DOCTYPE html>
<html>

<head>
  <script data-require="[email protected]" data-semver="1.3.17" src="https://code.angularjs.org/1.3.17/angular.js"></script>
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
</head>

<body ng-app="myApp">
  <div ng-controller="myController">
    <label>Var1</label>
    <input ng-model="var1">
    <br/>
    <label>Var2</label>
    <input ng-model="var2">
  </div>
</body>

</html>
like image 55
yvesmancera Avatar answered Dec 05 '25 01:12

yvesmancera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!