Hitesh.Aneja Hitesh.Aneja - 8 months ago 70
AngularJS Question

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

I have registered my listener to a $broadcast event using $on function

$scope.$on("onViewUpdated", this.callMe);

and I want to un-register this listener based on a particular business rule. But my problem is that once it is registered I am not able to un-register it.

Is there any method in AngularJS to un-register a particular listener? A method like $on that un-register this event, may be $off. So that based on the business logic i can say

$scope.$off("onViewUpdated", this.callMe);

and this function stop being called when somebody broadcast "onViewUpdated" event.


I want to de-register the listener from another function. Not the function where i register it.


This is found in the source code :) at least in 1.0.4. I'll just post the full code since it's short

  * @param {string} name Event name to listen on.
  * @param {function(event)} listener Function to call when the event is emitted.
  * @returns {function()} Returns a deregistration function for this listener.
$on: function(name, listener) {
    var namedListeners = this.$$listeners[name];
    if (!namedListeners) {
      this.$$listeners[name] = namedListeners = [];

    return function() {
      namedListeners[indexOf(namedListeners, listener)] = null;

In your case you need to remember the return function

var offCallMeFn = $scope.$on("onViewUpdated", callMe);

//this will deregister that listener