2016-09-15 40 views
0

我想从文档的顶部记录窗口的偏移量,但jQuery的滚动不起作用。将香草javascript的滚动事件监听器工作在角?将香草javascript的滚动事件工作在angularjs

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; 
        } 
       }); 
+1

,你能否告诉我们你已经完成了什么以及控制器/指令在哪里等你正在实现这个? jQuery应该很好地检测滚动,尤其是在AngularJS(不是Angular 2) – JosephGarrone

+0

为什么你使用'restrict:C'?你是否认真地使用'owlCarouselItem'作为评论? –

回答

1

使用angular.element($窗口)试试这个代码:

.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() 
      }); 
     } 
    }; 
}); 

而且你能坚持指令body标签 这样 HTML:

<body scroll-dir> 
+0

我改进了你的代码,删除了冗余并添加了$ scope。事件监听器不是角度摘要循环的一部分。你应该向OP解释他们如何使用'canSwipeDown'。 –

+0

非常感谢不错的工作 – SuperComupter