0

As the title asks. Are they opposite? Also how can I remove an event from the $rootScope based on its name?

A simple example would be also welcome.

4

1 回答 1

3

$destroy is both an event that each scope would listen to and also a method on the scope to trigger that event manually.

It is primarily used to do any actions that you want while that scope is getting destroyed. Instances of scope getting destroyed are:

  1. Switching views via ng-view, the previous controller scope gets destroyed.
  2. A directive is instantiated and that element is removed from the DOM, this applies to all directives, within angular framework and custom.

While on the other hand $broadcast is just used to trigger events which are in current level or child level scope.

They are not the opposite.

For the second question on how you can remove the event from $rootScope.

Lets say you have refined an event listener:

$rootScope.$on("myEvent", function () {
//some code
});

Each event listener returns a deregister function. So you can just use something like:

var removeMyEvent = $rootScope.$on("myEvent", function () {
//some code
});

Whenever you want to remove the event listener you just call the deregister function.

removeMyEvent();

That should do the trick!

于 2013-10-18T17:27:34.060 回答