Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error thrown when $watch an object with circular references

Tags:

angularjs

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>
like image 731
Zach Avatar asked Jan 23 '26 07:01

Zach


1 Answers

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');
});
like image 145
Vadim Avatar answered Jan 26 '26 00:01

Vadim



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!