ng-repeat with track by over multiple properties

2019-01-26 04:32发布

I have a problem with angular ng-repeat directive. Currently I work on some project where from the API I get a list of items (some times it could be 1k items) and this list should be refreshed every 5 seconds (it is monitoring related project).

When the list length is a little bigger the website while re-rendering DOM could "slow". It comes out that angular regenerate the whole DOM (but 95% of item are the same ! )

One of the possible approach is to set "track by" expression for example to item.id. But here comes another problem, I also want regenerate items when for example descriptions was changed by other user. Since track by is expression to item.id changes in item.description didn't update item in DOM.

There is way to track by over multiple properties? Maybe some function? Or maybe do comparison by "hand" ?

Any ideas, code samples I would appreciate :)

UPDATE

what I discover when I set track by to item.id angular didn't re-crete html for items, just update value in already created element and it seems to be "faster" then removing and creating. Previously I though a little bit different.

FIX

For those who are looking for better performance over >1k items in ng-repeat USE track by item.id it will boost your performance ;)

3条回答
ゆ 、 Hurt°
2楼-- · 2019-01-26 04:58

Based my knowledge, the angularjs model is bind to the ui view, so the model will rerender via $apply or $digest once the value changed. so in your case, u wan bind the model value to ui view but also do not want to re-render the view if the value has not change,that is impossbile. this is what i know.

however, u can just manipulate the dom element. for example store the data to a variable

var x = [{id:"id1",value:"v1"},{id:"id2",value:"v2"}]

in html, manual append or using directive to append, then assign the id to the element,

<div id="id1">v1</div>

check and compare the value, based ur needs. once found, then angular.element("#yourid").text()

this will solve your browser resources consume problems.

查看更多
The star\"
3楼-- · 2019-01-26 04:59

You do not need to create a function to handle track by multi properties. You can do:

<div ng-repeat="item in lines track by item.id+item.description">
查看更多
Ridiculous、
4楼-- · 2019-01-26 05:00

As the comment suggested you could try something like this:

<select ng-model="item" ng-options="item.id as item.description for item in items track by itemTracker(item)">

In your controller:

$scope.itemTracker= function(item) {
  return item.id + '-' + item.description;
}

This might help with the number of DOM elements being re-rendered when the list changes.

查看更多
登录 后发表回答