2014-10-12 83 views
3

當$觀看具有循環引用的對象時,例如, x.y = y; y.x = x;

錯誤:引發了太多的遞歸。請參閱下面的代碼。

如何自定義$ watch行爲?或爲對象創建一個自定義的「equals()」函數?

<!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> 

回答

1

您可以在手錶中指定自定義功能。例如。

$scope.$watch(function() { 
    //custom equality handler, return a value that when changed will fire the handler 
}, function(newVal) { 
    console.log('complex changed'); 
}); 
+0

謝謝。是個好主意! – Zach 2014-10-12 02:56:08

相關問題