Angularjs scope.$apply in 指令的滚动监听器 [英] Angularjs scope.$apply in directive's on scroll listener

查看:27
本文介绍了Angularjs scope.$apply in 指令的滚动监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下指令来确定用户是否已滚动到页面底部 - 150px 并设置正在侦听的范围变量并加载以下页面.它工作正常.

I am using the following directive to find out if the user has scrolled to the bottom of the page - 150px and set a scope variable which is being listened to and the following page is loaded. It works fine.

我担心的是 scope.$apply() 被多次调用.我需要调用 $apply() 指令才能工作,但我不确定多次调用它是否会导致问题.

My concern is that scope.$apply() is being called multiple times. I need to call $apply() for the directive to work but i am not sure if calling it multiple times can cause problems.

有什么想法吗?

谢谢.

myMod.directive('scrollDetection', 

function () {

    return {
        restrict: 'AE',
        link: function postLink(scope, element, attrs) {

            var last_scroll_top = 0;

            element.bind("scroll", function() {

                var scroll_top = this.scrollTop,
                    scroll_height = this.scrollHeight,
                    height = this.offsetHeight,
                    offset = 150;

                    if (scroll_top > last_scroll_top) {

                        if ((scroll_top + height + offset) >= scroll_height) {

                            scope.requestPage = true;
                            scope.$apply();

                        }

                    } 

                last_scroll_top = scroll_top;

            });
        }
    };
});

推荐答案

它处于某种状态,所以我认为它没有问题.为了提高性能,还要检查是否 scope.requestPage === false 因为如果已经是这样,则无需将其更改为 true.在单独的方法中处理条件以整理代码可能会很好.顺便说一下,我注意到滚动手表在资源方面非常昂贵,我建议在移动设备上禁用它.

It is in a condition so I don't think there is a problem with it. For added performance, check also if scope.requestPage === false as there is no need to change it to true if it's already the case. It might be good to handle the conditions in a separate method to tidy up your code. By the way, I noticed that a watch on scrolling is very expensive in terms of resources, I suggest disabling it for mobiles devices.

这篇关于Angularjs scope.$apply in 指令的滚动监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆