gpt4 book ai didi

javascript - 当用户无限滚动并删除以前数据的dom元素时,Angular js避免重复数据

转载 作者:行者123 更新时间:2023-11-28 06:11:51 28 4
gpt4 key购买 nike

我正在研究 Angular-js 无限滚动(没有 jquery)我想在加载时显示前 3 个数据,当用户滚动时它从数组 j-son 对象加载下 3 个数据。问题是,我可以在加载时加载前 3 个数据,但在滚动时它会再次加载前 3 个数据而不是显示接下来的 3 个数据。而且如果用户向下滚动以获取下一组数据它应该同时显示数据如果用户向上滚动 mans 显示上一组数据(基于分页的概念)。

以下数组用于解析 Controller 中的数据:

var app = angular.module('Demo', []);

app.controller('VerticleDemo', function($scope) {

$scope.items = [];
$scope.Arr = [{
"Select": "11",
"PhotoCount": "12"
}, {
"Select": "21",
"PhotoCount": "22"
}, {
"Select": "31",
"PhotoCount": "32"
}, {
"Select": "1",
"PhotoCount": "1"
}, {
"Select": "71",
"PhotoCount": "72"
}, {
"Select": "441",
"PhotoCount": "90"
}, ];

$scope.addItems = function() {
for (var i = 0; i < 3; i++) {

$scope.items.push($scope.Arr[i]);

}
};


$scope.addItems();
});
    .scroll-loader {
background: #f7f7f7;
height: 90px;
border: 3px solid #d2d2d2;
margin-bottom: 20px;
overflow: auto;
padding: 10px 0;
border-radius: .5rem 0 0 .5rem;
}
.scroll-loader li {
list-style: none;
border-bottom: 1px solid #aaa;
padding: 5px;
margin-bottom: 3px;
}

我不知道如何消除重复数据。我也尝试了不同的方法来避免这个问题。js-fiddle 链接如下: https://jsfiddle.net/sathishkti/96qhssfe/15/帮助解决这个问题。

最佳答案

问题出在您的 addItems() 中:

您总是将元素 0 添加到 3,您想要做的是创建一个 offSet 变量,它将跳过已经显示的元素。每次实例化滚动时,您都可以将其递增 X。为了便于使用,我将数字 3 存储在一个变量中。但是,我建议将其作为指令的一部分,以便您可以将其设置在 html 元素上以获得灵 active 。

var app = angular.module('myApp',[]);
app.controller('tstrll', function($scope) {

$scope.items = [];
$scope.Arr = [{
"Select": "11",
"PhotoCount": "12"
}, {
"Select": "21",
"PhotoCount": "22"
}, {
"Select": "31",
"PhotoCount": "32"
}, {
"Select": "1",
"PhotoCount": "1"
}, {
"Select": "71",
"PhotoCount": "72"
}, {
"Select": "441",
"PhotoCount": "90"
}, ];

$scope.numberOfItems = 3;
$scope.offSet = 0; //save the offset.
$scope.addItems = function() {
if ($scope.offSet <= $scope.Arr.length) //make sure it stops when there are NO new elements.
{
//increase the loop to match the offset to grab new values
for (var i = $scope.offSet; i < $scope.offSet + $scope.numberOfItems; i++) {

$scope.items.push($scope.Arr[i]);

}
$scope.offSet += $scope.numberOfItems; //increment the offset by 3.
}
};


$scope.addItems();
});


app.directive('infiniteScroll', [ "$window", function ($window) {
return {
link:function (scope, element, attrs) {
var offset = parseInt(attrs.threshold) || 0;
var e = element[0];

element.bind('scroll', function () {
if (e.scrollTop + e.offsetHeight >= e.scrollHeight - offset) {
scope.$apply(attrs.infiniteScroll);
}
});
}
};
}]);

演示 here

关于javascript - 当用户无限滚动并删除以前数据的dom元素时,Angular js避免重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36121208/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com