Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - Scroll event is not fired inside directive - angular.js

I'm stucked with problem. I have a directive for infinite-scroll where I listen for scroll event. The problem is that scroll event is only fired when I'm binding to $window:

angular.element($window).bind('scroll', function () {
  console.log('Gogo!'); //works!
});

element.bind('scroll', function () {
  console.log('Gogo!'); //doesn't work... :(((
});

Directive is inside ng-view I found this question, looks very similar to my problem - Binding to events in a directive which is inside a ng-view doesn't work

Anybody knows how to solve this?

My directive:

directives.directive('scrolly', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var raw = element[0];

            element.bind('scroll', function () {
                if (raw.scrollTop + raw.offsetHeight > raw.scrollHeight) {
                    scope.$apply(attrs.scrolly);
                }
            });
        }
    };
});

My view:

<ul class="items-wrap" scrolly="showMore()">
   <li class="item" ng-repeat="item in items">{{item.name}}</li>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's likely because the element you're binding to doesn't "scroll".

The node that you're actually scrolling (the document, or maybe a div with a scroll overflow) is the thing that actually fires the event.

Try injecting $document into your directive and setting up the scroll event on that:

$document.bind('scroll', function (){});

Also, ditch the if statement on the inside of handler until you're sure you have the event firing properly, then add it back.

Just to start:

app.directive('scrolly', function ($document) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {

            $document.bind('scroll', function () {
                scope.$apply(attrs.scrolly);
            });
        }
    };
});

Then work in your examination of the element positioning and other logic.

I hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...