Skip to content
Advertisement

How to unbind $on in Angular?

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.

Advertisement

Answer

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();
        };      
    })
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement