Reputation: 9126
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
Reputation: 2925
It actually wouldn't cause an infinite loop since the watch would stop being fired once both vars are equal.
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