2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

If a scope is terminated, two similar "$destroy" events are fired. What are they used for, and why are there two?

If a scope is terminated, two similar "$destroy" events are fired. What are they used for, and why are there two?
userimage
1st AngularJS event, "$destroy", and the second one is a jqLite / jQuery event "$destroy". The first one can be used by AngularJS scopes where they are accessible, such as in controllers or link functions.
By considering the two below happening in a directive's postLink function. The AngularJS event:
scope.$on('$destroy', function () {
  // handle the destroy, i.e. clean up.
});

And
element.on('$destroy', function () {
  // respectful jQuery plugins already have this handler.
  // angular.element(document.body).off('someCustomEvent');
});

The jqLite / jQuery event is called whenever a node is removed, which may just happen without scope teardown.
Answer is