C
C
crazyjs2015-04-11 20:06:56
JavaScript
crazyjs, 2015-04-11 20:06:56

Why does angularJS have $destroy?

Explain with examples for what purposes it is used:
scope.$on('$destroy', function() {})

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2015-04-11
@crazyjs

Example 1
Let's provide a directive for the bootstrap tooltip.
In the link function we write elem.tooltip({ /* opts */);
Let's say we have a table with 10 rows - tr, via ngRepeat.
We pressed the button in one of the tds, the tooltip opened. While it hangs, the line disappears due to some condition, let's say filter. BINGO! tooltip will remain. To remove it, in the link function of the directive, you need to write something like this code:

scope.$on('$destroy', function() {
  elem.tooltip('destroy');
}

Controller communication. Sometimes it is not always convenient to use factories / services for this. If the deregistrator function is not called, the event handler will remain in $rootScope forever and will be called.
function FooCtrl($rootScope) {
  this.someMethod = function() {
    // some code ...
    if (someCondition) {
      $rootScope.$emit('someEvent');
    }
  }
}

function BarCtrl($scope, $rootScope) {
  var deregFn = $rootScope.$on('someEvent', function() {
    // some code ..
  };

  $scope.$on('$destroy', function() {
    deregFn();
  });
}

K
kwolfy, 2015-04-11
@kwolfy

angular.ru/api/ng.$rootScope.Scope#$destroy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question