I have the following code inside of a directive and I want to make sure it gets cleaned up when the scope is destroyed. I've looked online as well as the code and I was wondering how do I unbind an element.
var window = angular.element($window);
window.bind("resize", function(e){
abc();
});
Solution:
var abc = function() {};
var window = angular.element($window);
window.bind('resize', abc);
scope.$on('$destroy', function(e) {
window.unbind('resize', abc);
});
Unbind the function from window
when the directive's scope gets destroyed. Hence in your directive, you'll invoke a clean up function on the scope's destroy's event:
$scope.$on('$destroy', cleanUp);
Create a cleanUp
function and call the jQuery's unbind function.
There is an example in this SO entry, but with the off
function instead (which seems similar to unbind
, but unavailable in jqLite). Also per this SO entry, you might have to name your function as you'll need to reference it again as a parameter in the unbind
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With