J-bob
J-bob

Reputation: 9126

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
})

Upvotes: 3

Views: 1495

Answers (1)

yvesmancera
yvesmancera

Reputation: 2925

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>

Upvotes: 3

Related Questions