qz.com の行でプロトタイプを構築しようとしています。
アプローチは次のとおりです。
- ページの一番下までスクロールするときに、次のコンテンツをロードする関数呼び出しを行います。
- 同じ関数は、$location.path(url) または window.history.pushState() を使用して URL を変更します。
- 上にスクロールすると、表示されているセクションに基づいて 2 つのいずれかが URL を変更します。
ポイント 2 で行き詰まっています。$location または pushState を呼び出すたびに、ページがリロードされてループに入ります。
コードは次のとおりです。
コントローラ
controller('BlogCtrl', function ($scope, $location, $http) {
$scope.blogs = [];
var counter = -1;
$scope.loadNext = function() {
$http.get('/api/blogs').success(function(data) {
//console.log(counter);
$scope.blogs.push(data[counter]);
//$location.path('blog/'+data[counter].url);
//window.history.pushState('blog/'+data[counter].url);
});
counter+=1;
}
$scope.loadNext();
}))
指令
directive('scrollLoad', function () {
return function (scope, elm, attr) {
// Scroll should have been there instead of hover event.
// For some reason, scroll wasn't being detected, hence used hover function.
// It is essentially a hack. Need to revisit this piece.
elm.on('hover', function() {
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
scope.$apply(attr.scrollLoad);
}
}
});
}
});
html
div
div(scroll-load="loadNext()", ng-repeat="blog in blogs")
h1 {{blog.title}}
p {{blog.content}}
レポへのリンク: https://github.com/fotuzlab/two1/
別のアプローチについて提案がある場合は、ここで回答してください