Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 990
JasonY Avatar asked Feb 15 '26 11:02

JasonY


1 Answers

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!

like image 128
JasonY Avatar answered Feb 17 '26 06:02

JasonY



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!