【发布时间】:2016-04-10 03:55:07
【问题描述】:
我是 Angular 新手,以前使用过 jquery。
我设置了一个指令,当用户几乎在文档的底部时,监听滚动以触发 http.get 请求。一切正常,但我无法避免该事件一次触发很多时间。
如果你有一些很棒的建议,这里有一些代码!
html:
div(class="home-flex", ng-scroll, infinite-request="addMore()", ng-disabled)
div(class="home-article", ng-repeat="article in articles", ng-cloak)
img(class="home-article-image", ng-src="{{ article.imageUrl }}", ng-cloak)
指令:
nemi.directive('ngScroll', function($window, $document){
return {
link: function(scope, element, attrs){
$document.on('scroll', function(element){
var height = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
// console.log("window height : " + $window.innerHeight)
// console.log("scroll from top : " + $window.pageYOffset);
// console.log("scroll from top + window height : " + ($window.innerHeight + $window.pageYOffset))
// console.log("doc height : " + height);
// console.log("scroll/doc : " + $window.pageYOffset/height);
if ((($window.pageYOffset + $window.innerHeight)/height) > 0.6) {
console.log("trigger");
scope.$apply(attrs.infiniteRequest);
}
})
}
}
})
找到我的控制器:
nemi.controller('homeController', [ '$scope', '$http', '$window', function($scope, $http){
$http.get('/articles').success(function(res){
$scope.articles = res;
}).error(function(data){
console.log(data);
});
var wait = true;
$scope.addMore = function() {
if (wait === true) {
wait = false;
console.log("trigger");
$http.get('/articles').success(function(res) {
res.forEach(function(elem){
$scope.articles.push(elem);
})
wait = true;
}).error(function(){
console.log("scroll failed");
})
}
}
}]);
我用“等待布尔值”来阻止该功能的悲惨尝试,但并没有一次将我从许多请求中解救出来。
我用 ng-disabled 尝试了不同的东西,但到目前为止对我没有任何效果
【问题讨论】:
标签: angularjs angularjs-directive angularjs-scope angularjs-http