JasonY JasonY - 2 years ago 92
Javascript Question

angular controller scope not destroying variables when ui-router changes state

In my app, I've noticed that when I change states, the $scope variables still exists and get logged on a timeout. Why is this? How can I remove it completely so it doesn't take up heap memory?

what is mean is, after a state change from the controller

$scope.$on("$destroy",function(){
setTimeout(function(){
console.log($scope.whatever);
},10000);
});


$scope.whatever still logs meaning it was never removed! What is going on? I thought a destroy event would destroy everything within the scope as well?

Answer Source

The reason for this is, by console.logging the $scope variable in the timeout, I am referencing it so javascript will avoid Garbage Collection in the scope until it executes and is no longer referenced, there is no weak referencing in javascript like there is in java.

This should be avoided at all costs because it creates massive memory leaks in angular! Make sure the variables are not referenced anywhere when the scope is destroyed!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download