gpt4 book ai didi

javascript - AngularJS 延迟渲染(不是延迟加载 View )

转载 作者:行者123 更新时间:2023-12-03 08:36:23 26 4
gpt4 key购买 nike

假设我有很多(3000+)项目想要在具有固定高度和 overflow: auto 的 div 中渲染(在 ng-repeat 中) >,所以我会得到 N 个可见项目和其余项目的滚动条。

我猜对这么多项目做一个简单的 ng-repeat 可能会花费很多时间。有没有办法让 AngularJS 只渲染那些可见的 N 项?

编辑:

无限滚动不是我想要的。我希望用户能够滚动到列表的任何点,所以我确实想要一个类似文本编辑器的行为。换句话说:我希望滚动包含所有项目的“高度”,但只在 DOM 中放置几个​​项目。

最佳答案

This answer provides an approach for lazy-rendering only items currently in-view, as defined by the edit to the original question. I want the user to be able to scroll to any point of the list, so I literally want a text editor-like behavior. Said with other words: I'd like the scroll to contain the "height" of all the items, but place in the DOM just a few ones.

安装angular-inview在尝试这个之前先插件。

为了获得滚动高度,您需要一些东西来容纳数组项的空间。所以我会从 3000 个简单项目的数组开始(或者与无限滚动结合到您想要的任何程度。)

var $app = angular.module('app', ['infinite-scroll']);

$app.controller('listingController', function($scope, $window) {
$scope.listOfItems = new Array($window._bootstrappedData.length);
$scope.loadItem = function($index,$inview) {
if($inview) {
$scope.listOfItems[$index] = $window._bootstrappedData[$index];
}
}
});

由于我们正在讨论灵活的高度,因此我会为您的内容预渲染的内容创建一个占位符。

<div ng-controller="listingController">
<ul>
<li ng-repeat="item in listOfItems track by $index" in-view="loadItem($index,$inview)" style="min-height:100px"><div ng-if="item">{{item.name}}</div></li>
</ul>
</div>

使用ng-if将防止渲染逻辑不必要地运行。当您将某个项目滚动到 View 中时,它将自动显示。如果您想等待一秒钟看看用户是否仍在滚动,您可以在 loadItem 方法中设置一个超时,如果相同的索引在合理的时间段内被推出 View ,则该超时会取消。

Note: If you truly wanted to avoid putting anything in the DOM, you could set your scrollable area to a specific multiple of your "placeholder" height. Then you could create a directive that uses that height to determine the indexes of the items that should be displayed. As soon as you display new items, you'd need to add their heights to the total and make sure you position them at the right spot and make sure your directive knows how to interpret those heights into evaluating the next set of displayed elements. But I think that's way too radical and unnecessary.

关于javascript - AngularJS 延迟渲染(不是延迟加载 View ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33202369/

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