当我们用手机逛微博时,或者逛空间时,常常遇到这么一个功能,当手机页面上的滚动条滑动到底端时,页面底端的数据会慢慢的加载出来,随着我们不断的向下滑动,页面上的数据不断增多。那么,这个功能用AngularJS怎么实现哪?
以前小编是用点击的方式实现“加载更多”,这样感觉用户的体验度差,而现在,我们可以用AngularJS中自己封装的指令实现此功能,下面是具体的代码。
app.directive('infiniteScroll', ['$rootScope', '$window', '$timeout', function ($rootScope, $window, $timeout) {
return {
link: function (scope, elem, attrs) {
var checkWhenEnabled, handler, scrollDistance, scrollEnabled;
$window = angular.element($window);
scrollDistance = 0;
if (attrs.infiniteScrollDistance != null) { //接收并返回触发加载更多的距离
scope.$watch(attrs.infiniteScrollDistance, function (value) {
return scrollDistance = parseInt(value, 10);
});
}
scrollEnabled = true;
checkWhenEnabled = false;
if (attrs.infiniteScrollDisabled != null) {
scope.$watch(attrs.infiniteScrollDisabled, function (value) {
scrollEnabled = !value;
if (scrollEnabled && checkWhenEnabled) {
checkWhenEnabled = false;
return handler();
}
});
}
handler = function () {
var elementBottom, remaining, shouldScroll, windowBottom;
windowBottom = $window.height() + $window.scrollTop();//所选中元素展示框的高度 + 滑动条向下滑动的距离
elementBottom = elem.offset().top + elem.height(); //页面的总长度
remaining = elementBottom - windowBottom;
shouldScroll = remaining <= $window.height() * scrollDistance;
if (shouldScroll && scrollEnabled) { //达到可加载距离
if ($rootScope.$$phase) {
return scope.$eval(attrs.infiniteScroll);
} else {
if (remaining <= 50 ) {
scope.loadMore(); //在此调用加载更多的函数
}
return scope.$apply(attrs.infiniteScroll);
}
} else if (shouldScroll) {
return checkWhenEnabled = true;
}
};
$window.on('scroll', handler); //监控scroll滑动则运行handler函数
scope.$on('$destroy', function () { //离开页面则关闭scroll与handler的绑定
return $window.off('scroll', handler);
});
return $timeout((function () {
if (attrs.infiniteScrollImmediateCheck) {
if (scope.$eval(attrs.infiniteScrollImmediateCheck)) {
return handler();
}
} else {
return handler();
}
}), 0);
}
};
}
]);
加载更多函数
$scope.loadMore = function () {
这里写你分页查询的函数。
}
以上就是directive中的代码和加载更多的代码,接下来在html中要监控的dom元素顶端加入以下代码:
<div infinite-scroll="" infinite-scroll-distance="1"></div>
就这样,功能就实现了,加载更多的代码自己可以随便写,能实现功能就行,我这写的复杂了,其实就是个分页查询,但是封装的这个指令比较复杂,大家可以好好的研究一下,指令里面用到了两个scope.$watch,第一个是用来监测页面滚动条滚动的距离,一个是监测滚动条是否滚动到底端,然后确定是否调用handler()。