Jesse
Jesse

Reputation: 975

Memory Management in AngularJS

I am new to angular, so maybe I'm going about this completely wrong. I am attempting to make a treeView with angularJS directives. The code that I have so far accomplishes this, except that there appears to be a memory leak as each time the tree view reloads it slows down, and eventually crashes the browser.

I have created the following two directives to accomplish my task jscTreeView and jscTreeNode

This fiddler has my source, it builds you a random tree, and gives you the ability to choose the amount of nodes in the tree. If you bump that number up to a higher number, and reload several times you will notice that it progressively slows down to each time.

Any ideas on how to clean up after myself would be greatly appreciated, thanks.

Edit:

This fiddler is a second attempt with this one I went in a completely different direction. It is much more efficient, and the code is more clean in my opinion. However, this one has an issue too. periodically, and seemingly randomly on refresh of the tree this one throws an infinite digest exception.

Note: not all of the functionality that was in the former tree is in the current tree yet. That is just because I have not programmed it yet.

Upvotes: 3

Views: 999

Answers (1)

Jesse
Jesse

Reputation: 975

As the discussion in the comments indicates, I was creating, but never properly releasing, scopes in my tree view. While the solution was not very easy to figure out it is actually quite an easy solution, and clarified things a lot for me.

What I needed to do was make a clone of the root scope of my tree var newScope = scope.$new();, I then built all of the rest of the subtrees as well as their associated nodes and compiled with the cloned scope newScope. After the compile it stores the cloned scope into a variable private to the directive lastScope = newScope;. When the watch property is updated, and calls back to my directive the last cloned scope is destroyed lastScope.$destroy();. Destroying that cloned scope automatically destroys any child scope created beneath it (the nodes, as well as the subtrees). A new clone of the scope is created, and the process is repeated, thanks to @Jorg's tool to count scopes, I can see that everything is being cleaned up nicely on each iteration. Here is a fiddle to the solution.

Upvotes: 1

Related Questions