I've read many many articles on the topic of when to use scope.$on("$destroy") but I haven't been able to identify when to apply it in practice. I'm not looking for a "In this case you would..." answer" I'm looking for a clarification to know myself when (to/to not) worry about applying it.
here's a couple of the articles I've read.
Angular Documentation for scope
Always trigger the destroy event before removing dom elements
If a dom element is removed are it's listeners removed as well
How the destroy event affects the scope tree
given a very simple directive that doesn't even have it's own scope. This directive scrolls an item into the screen and keeps it there.
angular.module("scrollIf").directive("scrollIf", ["$window", "$timeout",
function ($window, $timeout) {
"use strict";
return {
link: function (scope, element, attrs) {
var css = attrs.scrollIf;
var scrollElement = $window.document.getElementsByClassName(css)[0];
var handler = element.on("click", function (event) {
scope.$parent.$digest(); //update everything first
$timeout(function () {
var elementViewPortTop = element[0].getBoundingClientRect().top + (element[0].getBoundingClientRect().height / 2);
var scrollPosition = scrollElement.scrollTop + (elementViewPortTop - event.clientY);
scrollElement.scrollTop = scrollPosition;
}, 1);
});
}
};
}]);
given this example, do I need to worry about $destroy? I am attaching a handler directly to the dom, not to scope. so when the parent gets destroyed is this example leaving detached objects in memory that don't have references?
Also, why is $scope.$on("click")
different than element.on("click")
? If I use the controllerAs
syntax and bind to controller. I don't inject the $scope
service into my directive. In that case is $scope.$on
the same as link's scope.$on
?