简体   繁体   English

angular.js ng-repeat +无限滚动导致过多观察者

[英]angular.js ng-repeat + infinite scroll causing too many watchers

I have this code: 我有以下代码:

<section infinite-scroll='load()'>
    <div class="product" ng-repeat="product in products | limitTo:total">
        ..
    </div>
 </section>

In controller: 在控制器中:

$scope.products = []; // array of all products
$scope.load = function() {
   $scope.total += 5;
};

When an user scrolls to the bottom controller increases limitTo variable so he would see 5 more products. 当用户滚动到底部时,控制器会增加limitTo变量,因此他将看到5种产品。 If there are 40 products site has 4700 watchers . 如果有40个产品的站点有4700个观察者 If he keeps scrolling there might be even 12k watchers.. Any ideas how to fix that? 如果他继续滚动,甚至可能会有12,000个观看者。.有什么想法解决该问题吗? Each product has various inputs for adding to cart action. 每个产品都有添加到购物车操作中的各种输入。

I was taking a look for virtual repeat(eg this ), but it's using a container with fixed height so it would be ugly and completely wrong to scroll products like that. 我一直在寻找虚拟重复(例如this ),但是它使用的是固定高度的容器,因此滚动这样的产品将是非常丑陋且完全错误的。

Angular will place a watch on every binding expression that you have. Angular将监视您拥有的每个绑定表达式。 You'll have to reduce the number of binding expressions in your code to see a decrease in the number of watches. 您必须减少代码中绑定表达式的数量才能看到监视数量的减少。

However you can try to alleviate the problem by using track by to help angular figure out what shouldn't be re-evaluated. 但是,您可以尝试使用track by来缓解问题,以帮助您确定不应重新评估的内容。

 <section infinite-scroll='load()'> <div class="product" ng-repeat="product in products | limitTo:total track by $index"> .. </div> </section> 

In order to remove unneeded watches consider rendering only what is visible to the user and replacing everything else with empty elements if possible. 为了删除不需要的手表,请考虑仅呈现用户可见的内容,并在可能的情况下用空元素替换其他所有内容。

You don't say whether the list is supposed to be editable or not. 您没有说清单是否应该是可编辑的。 That said, I don't think a monster list (thousands of elements) editable is feasible anyway. 也就是说,我认为可编辑的怪物列表(成千上万个元素)是不可行的。

In a project I'm working on we have the same use case as the one you present. 在一个我正在研究的项目中,我们拥有与您介绍的用例相同的用例。 So far, with about 5000 elements in the list, it seems to be working great: We have gone to great lengths to use one-time binding s and create efficient directories which frees up their watchers as quickly as possible. 到目前为止,列表中包含约5000个元素,这似乎工作得很好:我们竭尽全力使用一次性绑定 s并创建有效的目录,以尽可能快地释放其观察者。

For editing we pass on the element which is clicked on and open that in a separate context. 为了进行编辑,我们传递了被单击的元素,并在单独的上下文中将其打开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM