Preventing an infinite loop with two hours
I am looking for a method to prevent infinite loop when using two operators $watch
in angular. The idea is to change var1
, I want it to change var2
. When it var2
changes, I want it to change var1
. But this usually creates an endless loop. Is there a way to get around this? Below is a trivial example to demonstrate the problem. This code will be in the angular controller.
$scope.$watch('var1', function(newVal){
$scope.var2 = newVal
})
$scope.$watch('var2', function(newVal){
$scope.var1 = newVal
})
+3
source to share
1 answer
This will not actually cause an infinite loop as the clock will stop running when both vars are equal.
- Var 1 changed by user
- Var 1 clock is triggered and set var2 = var1;
- Wahr Var 2 watch and set var1 = var2;
- Since var 1 hasn't actually changed, the clock no longer starts, no endless loop occurs.
Here's a snippet that demonstrates 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="angular.js@1.3.17" 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>
+3
source to share