Angularjs scope.$apply in directive's on scroll listener

蹲街弑〆低调 提交于 2019-12-13 21:27:06

问题


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.

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.

Any thoughts?

Thank you.

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;

            });
        }
    };
});

回答1:


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.



来源:https://stackoverflow.com/questions/23833219/angularjs-scope-apply-in-directives-on-scroll-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!