【问题标题】:Will vanilla javascript scroll event work on angularjs香草javascript滚动事件是否适用于angularjs
【发布时间】:2016-09-15 06:32:09
【问题描述】:

我想记录窗口从文档顶部的偏移量,但 jquery 滚动不起作用。 vanilla javascript 滚动事件监听器会在 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;
                    }
                });

【问题讨论】:

  • 你能告诉我们你做了什么以及你在控制器/指令等的什么地方实现了这个吗? jQuery 应该可以很好地检测滚动,尤其是在 AngularJS(非 Angular 2)中
  • 你为什么使用restrict: C?您是否认真使用owlCarouselItem 作为评论?

标签: javascript angularjs


【解决方案1】:

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

您可以将指令粘贴到正文标记 像这样 HTML:

<body scroll-dir>

【讨论】:

  • 我改进了您的代码,删除了冗余并添加了 $scope.$apply;事件侦听器不是角度摘要循环的一部分。您可能应该向 OP 解释他们将如何使用 canSwipeDown
猜你喜欢
  • 2023-01-18
  • 1970-01-01
  • 2021-01-01
  • 2019-01-18
  • 2012-09-23
  • 2017-05-24
  • 2018-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多