I have a code that use $scope.$on one time on init and then in a function, so the code is executed multiple times. How can I unbind if first before I bind it again. I've try $scope.$off but there's not such function, https://docs.angularjs.org/api say nothing about $on. I'm using angular 1.0.6.
Asked
Active
Viewed 1.1k times
10
Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129
jcubic
- 61,973
- 54
- 229
- 402
-
possible duplicate of [How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on](http://stackoverflow.com/questions/14898296/how-to-unsubscribe-to-a-broadcast-event-in-angularjs-how-to-remove-function-reg) – Julien May 02 '14 at 09:02
2 Answers
30
If you don't un-register the event, you will get a memory leak, as the function you pass to $on will not get cleaned up (as a reference to it still exists). More importantly, any variables that function references in its scope will also be leaked. This will cause your function to get called multiple times if your controller gets created/destroyed multiple times in an application. Fortunately, AngularJS provides a couple of useful methods to avoid memory leaks and unwanted behavior:
- The $on method returns a function which can be called to un-register the event listener.
- Whenever a scope gets cleaned up in Angular (i.e. a controller gets destroyed) a $destroy event is fired on that scope. You can register to $scope's $destroy event and call your cleanUpFunc from that.
See the documentation
Sample Code:
angular.module("TestApp")
.controller("TestCtrl",function($scope,$rootScope){
var cleanUpFunc = $scope.$on('testListener', function() {
//write your listener here
});
//code for cleanup
$scope.$on('$destroy', function() {
cleanUpFunc();
};
})
suneetha
- 827
- 1
- 6
- 14
5
$scope.$on returns a function which you can call to unregister.
phylax
- 2,034
- 14
- 13
-
-
however, it's not comfortable because if you would like to unregister an event in a different function you need to pass the unregister function through different functions as a parameter – dude Sep 10 '15 at 11:20