0

I want to log the offset of window from the top of document but jquery scroll is not working. Will vanilla javascript scroll event listener work in angular?

app.directive('owlCarouselItem', function($touch, $timeout, $rootScope, $window){
    return {
        restrict: 'C',
        transclude: false,
        link: function(scope, element) {
            // this is the part of my directive the on scroll event is not firing
                $('html, body').on('scroll', function() {
                    if($(this).scrollTop() == 0){
                        console.log($(this).scrollTop());
                        canSwipeDown = true;
                    }else{
                        console.log($(this).scrollTop());
                        canSwipeDown = false;
                    }
                });
2
  • 1
    Can you show us what you've done and where in the controller/directive etc you are implementing this? jQuery should work fine to detect scrolling, especially in AngularJS (Not Angular 2) Commented Sep 15, 2016 at 6:34
  • why are you using restrict: C? are you seriously using owlCarouselItem as a comment? Commented Sep 15, 2016 at 9:54

1 Answer 1

1

Try this code using angular.element($window):

.directive('scrollDir', function($window) {
    return {
        restrict: 'EAC',
        link: function(scope, attrs, element) {
            var canSwipeDown = false
            // this is the part of my directive the on scroll event is not firing
            angular.element($window).on('scroll', function() {
                canSwipeDown = element.scrollTop() === 0
                scope.$apply()
            });
        }
    };
});

And you can stick directive to body tag like this HTML:

<body scroll-dir>
Sign up to request clarification or add additional context in comments.

1 Comment

I've improved your code, removed redundancies and added $scope.$apply; event listeners are not part of the angular digest cycle. You should probably explain to the OP how they would consume canSwipeDown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.