简体   繁体   中英

AngularJS: what is the usage of track by with ng-repeat

i am new in angular and i go through this doc https://docs.angularjs.org/api/ng/directive/ngRepeat but do not understand the objective of track by clause using with ng-option.

here are few usage

<div ng-repeat="n in [42, 42, 43, 43] track by $index">
  {{n}}
</div>

<div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  {{n}}
</div>

<div ng-repeat="model in collection track by model.id">
  {{model.name}}
</div>

<div ng-repeat="obj in collection track by $id(obj)">
  {{obj.prop}}
</div>

<div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
    {{model.name}}
</div>

track by is something close to order by clause in sql ?

if yes then how can i specify sort order like ASC or DESC ?

in last code track by and orderBy both use ....what they are doing. not clear what kind of output will come.

what is difference between orderBy & track by ?

orderBy is filter that i know. so track by is also a filter.

i know i am asking very basic question. basically posting here because things is not clear after reading it from doc. looking for some help and example to understand what track by does ?

how track by is different from orderby in terms of usage ?

ngRepeat uses a function to "keep track" of all items in the collection and their corresponding DOM elements

If a new item is added to the collection, ngRepeat will know that all other items already have DOM elements, and will not re-render them.

See the detail

If you have object for ngRepeat and it have any identity field (Like primary key value or Unique value), use it in track by.

Good thing is that if you are re-loading the list, dome will not re-render for existing items but only the new ones.

By default orderBy will be in ascending order. You can use "reverse" for descending order like

In HTML Template Binding

{{ orderBy_expression | orderBy : expression : reverse}}

In JavaScript

$filter('orderBy')(array, expression, reverse)

If you do need to repeat duplicate items, you can substitute the default tracking behavior with your own using the track by expression.

For example, you may track items by the index of each item in the collection, using the special scope property $index:

`<div ng-repeat="n in [42, 42, 43, 43] track by $index">

 {{n}}

</div>`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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