I tried to find if my angularjs code has memory-leak, but not found yet.
I've read some articles about javascript memory-leak, but it's not useful for angularjs application, since it uses bi-binding which hide most of DOM operation to users.
So I have another question: how to write memory-leaked application with angular? Is there any common mistake pattern that we should avoid?
Angular mostly handles it for you, but there are places where you need to think about memory. Since your services exists from the time they are created to when your application closes, it's easy to hog memory in such objects. Like if your implementing caching, you might end up holding cached references to objects that will never be used again, so you would need a strategy to release those objects.
Another place is in directives where you interact with the DOM. But as long as you listen to $scope.$on('$destroy', function () { /* Clean up code here */ }); and clean up after yourself, you should be fine.
If you use $timeout to execute a function that does not return null, you will get a memory leak. This is very easy to accidentally do in coffeescript, as it implicitly returns the value of the last line of a function
eg.
doSomethingEveryTenSeconds = ->
//do something here
$timeout(doSomethingEveryTenSeconds, 10000)
null #prevent memory leak
To answer this you really need to know Angular's garbage collection. It does a really good job. But if it thinks there is still a reference to an object or if something else is referencing it, then a memory leak can appear. You can use jQuery or any other library to create a circular reference via a DOM object.
Here's an example. http://plnkr.co/edit/nIt78S?p=preview
If you open controllers.js you'll see a jQuery $() to Angular $scope circular reference:
//*** CREATING MEMORY LEAK ***
$("#memory-leak").on('click', function() {
console.log("[HomeController " + myInstance + "] click()");
$scope.data.counter++;
});
Because the jQuery .on() method is attached to a div outside of the controller, it's never freed. You can test this by:
1) Opening the console
2) Navigating back and forth between Home and Data pages. Each time you do, notice a new Home Controller instance is created.
3) After you've created 3 or 4 instances, click the div that says "Memory Leak Test". You'll see 3 or 4 console logs from the above code, a memory leak!