I'm trying to unbind an event in my AngularJS directive within a function that is passed as the event handler to angular.element($window).on()
.
From this question, I've come to realise that to unbind from the current directive only, the same event handler must be passed to both angular.element().on()
and angular.element().off()
AngularJS - Unbind $window of an event from specific directive.
This is my controller method within a the object returned by the directive;
controller: function($scope, $element) {
var eventHandler = function() {
var windowBottom = $window.pageYOffset + $window.innerHeight;
var elementBottom = $element[0].getBoundingClientRect().bottom;
if (windowBottom > elementBottom) {
console.log($scope.stockID, this);
angular.element($window).off('scroll', this.bind(this));
}
};
angular.element($window).on('scroll', eventHandler.bind(eventHandler));
}
Any help understanding why this is failing to unbind the event would be much appreciated!
Note: I originally tried passing just eventHandler
to both the .on()
and .off()
functions, however I realised that this
wasn't referencing the eventHandler
function, hence why I've called it with .bind(eventHandler)
.