Can someone provide an example of a $destroy event for scopes in AngularJS?

Angularjs

Angularjs Problem Overview


Can someone please provide an example of scope's $destroy event? Here is the reference documentation from http://docs.angularjs.org/api/ng.$rootScope.Scope#$destroy

> $destroy() > > Removes the current scope (and all of its children) from the parent > scope. Removal implies that calls to $digest() will no longer > propagate to the current scope and its children. Removal also implies > that the current scope is eligible for garbage collection. > > The $destroy() is usually used by directives such as ngRepeat for > managing the unrolling of the loop. > > Just before a scope is destroyed a $destroy event is broadcasted on > this scope. Application code can register a $destroy event handler > that will give it chance to perform any necessary cleanup.

Angularjs Solutions


Solution 1 - Angularjs

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

Solution 2 - Angularjs

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSunnyShahView Question on Stackoverflow
Solution 1 - AngularjsSunnyShahView Answer on Stackoverflow
Solution 2 - AngularjsniaherView Answer on Stackoverflow