Question

I'm trying to get an infinity loading directive to work. So I created a binding for the window scroll event like this.

    angular.element($window).bind('scroll',function()
    {
        _onScroll($scope);
    });

In my _onScroll method I log to the console the scroll position like this.

    var $wnd = angular.element($window);
    var pageTop = $wnd.scrollTop() + $wnd.height();
    var markerTop = $loadMore.offset().top;

    console.log('pageTop: '+pageTop+' markerTop: '+markerTop);

This works except when I navigate to another part of the app, and come back to the page with the infinity directive.

The problem is that _onScroll is getting called duplicated times. Each time I navigate back to the infinity directive adds an additional call to _onScroll

For example;

First time I'll see in the console.

pageTop: 300 markerTop: 1000
pageTop: 600 markerTop: 1000
pageTop: 900 markerTop: 1000

The second time I'll see two lines printed for each scroll event like this.

pageTop: 300 markerTop: 1000
pageTop: 300 markerTop: 1000
pageTop: 600 markerTop: 1000
pageTop: 600 markerTop: 1000
pageTop: 900 markerTop: 1000
pageTop: 900 markerTop: 1000

And so on...

It appears that the angular.element($window).bind(..) is persistent and that I need to somehow unbind it when the directive is no longer used.

How would I do that? Should be noted that this directive does not have an isolated scope so I can't watch for the scope to be destroyed.

Was it helpful?

Solution

You can bind to the jQuery destroy event in the directive:

element.on('$destroy', function() {
    // unbind
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top