When $watch an object with circular references, e.g. x.y = y; y.x = x;
An error: too much recursion is thrown. See the code below.
How to custom the $watch behavior? or create a custom 'equals()' function for the object?
<!DOCTYPE html>
<html>
<body>
<div ng-app="" ng-controller="testController">
{{complex .v}},{{complex.y.v}}
</div>
</body>
<script>
function testController($scope) {
var x = { v: 5, y: null };
var y = { v: 6, x: x };
x.y = y; // <---------------- circlular ref
$scope.$watch('complex', function(newVal){
}, true);
$scope.complex = x;
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</html>
You could specify a custom function in your watch. E.g.
$scope.$watch(function() {
//custom equality handler, return a value that when changed will fire the handler
}, function(newVal) {
console.log('complex changed');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With