How to avoid refreshing ng-repeat DOM list when array is updated

陌路散爱 提交于 2019-12-03 00:25:32
Peter Goodheart

I found a solution!

After poking around and further checking the "track by" with my scenarios, I can see that it actually does more what it says:

1) If you have a collection of objects, with each object having: id, name, description, you can, using 'track by' choose a property that it connects to, so, on retrieving a new collection of objects from a webservice, it will not render the DOM object belonging to the value.

2) Most importantly, and what I was after: If an object with an existing id arrives from the server with fx a changed name, will it be reflected in the array collection on the object with that id? Yes, it will! So, "track by" will actually check the properties of the incoming object and replace the old object and still leave the id alone. That's intense.

It's also worth noting that "track by" works also with other directives than ng-repeat, such as select.

I made a small demo, for other people who might be confused about how everything works... but it seems to be cool!

    <div ng-repeat='country in countryArray track by country.id'>
        {{country.id}}
        {{country.name}}
        <input type="checkbox"></input>
    </div>

    <div>
        <select ng-model='nonExisting' 
          ng-options='country.name for country in countryArray 
            track by country.id'></select>
    </div>
</div>

http://jsfiddle.net/KUf8C/

AngularJS track by support on ng-repeat can help you here. By default it uses generated $$hashekey but this behaviour can be overriden. So if your records have unique ids you can use the track by to take care that the DOM is not reconstructed.

Ben Nadel did a post on this http://www.bennadel.com/blog/2556-Using-Track-By-With-ngRepeat-In-AngularJS-1-2.htm

You should use an object to keep track of the selected emails.

Basically you keep a selected object in your scope and use it to keep track of which emails are selected. For example if email 7 is selected then make selected[7] = true.

So in psuedoish code

selected = {}

user selects email 7 then selected[7] = true

selected == {
  7: true
}

user unselects email y then selected[7] = false

selected == {
  7: false
}

Here is a jsFiddle that I might have gotten a little carried away with. I use the technique described above to keep track of which emails are selected.

http://jsfiddle.net/8kY9u/11/

In the fiddle I keep track of new emails in a similar fashion too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!