Angularjs scope.$apply in directive's on scrol

2019-08-28 08:46发布

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条回答
太酷不给撩
2楼-- · 2019-08-28 08:56

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.

查看更多
登录 后发表回答