Angularjs范围。$适用于上滚动监听指令的 [英] Angularjs scope.$apply in directive's on scroll listener
问题描述
我使用下面的指令找出如果用户已经滚动到页面的底部 - 150像素,并设置其正在听取和下面的页面加载一个范围的变量。它工作正常。
我担心的是范围。$适用()被调用多次。我需要调用$申请()的指令工作,但我不知道是否调用它多次,可能会出现问题。
有什么想法?
感谢您。
myMod.directive('scrollDetection',功能(){ 返回{
限制:AE,
链接:功能postLink(范围,元素,ATTRS){ 变种last_scroll_top = 0; element.bind(滚动功能(){ VAR scroll_top = this.scrollTop,
scroll_height = this.scrollHeight,
身高= this.offsetHeight,
偏移= 150; 如果(scroll_top> last_scroll_top){ 如果((scroll_top +高度+偏移量)> = scroll_height){ scope.requestPage = TRUE;
。范围$适用(); } } last_scroll_top = scroll_top; });
}
};
});
这是一个条件,所以我不觉得有什么出了问题。为了增加性能,同时检查 scope.requestPage ===虚假
因为没有必要将其更改为true,如果它已经如此。这可能是很好的处理条件,在一个单独的方法来整理你的code。顺便说一句,我注意到,在滚动的手表是在资源方面非常昂贵的,我建议禁用它的移动设备。
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;
});
}
};
});
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范围。$适用于上滚动监听指令的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!