In the project, a problem has been encountered, in the ng-repeat in angular, the order by is invalid when track by and by are in use.
Let's take a look at how Ng-repeat works.
Here is a demo:
1. Original state
Index.html
<! DOCTYPE html>
Controller.js
/**
* * *
/var app = Angular.module (' app ', []);
App.controller (' Ctrl ', function ($scope) {
$scope. peoples=[{
age:12,
name: ' Jesus ',
Country: ' Spain '
},
{
age:21,
name: ' Dave ',
Country: ' USA '
},
{
age:19,
name: ' Carolina ',
Country: ' Italy '
}];
$scope. Order = ' name ';
};
The effect is as follows:
We can see that ng-repeat exactly shows all of our data.
2. Then make a change in the index.html,
<div ng-repeat= "person in peoples | Orderby:order" >
The effect is as follows:
We see here that the ng-repeat are sorted by name according to our settings.
3. Let's do the change again.
<div ng-repeat= "person in peoples track by Person.age | Orderby:order" >
The effect is as follows:
By the time we see it, the by-by is invalid.
4. After angular1.2, a new attribute was added, track by. When there's no such attribute
<div ng-repeat= "person in Peoples" >
Ng-repeat The default is to add a $ $hashkey for Each loop object, this property is self increasing, somewhat similar to the ID in the database, but a string type.
When our data changes (without track by), Ng-repeat refreshes our DOM tree, where the refresh refers to removing all existing elements and then rebuilding the DOM nodes and numbering them. This can cause our pages to refresh frequently and may result in a reduction in cotton or performance.
When we add track by this property
<div ng-repeat= "person in peoples track by Person.age" >
At this point, Ng-repeat will mark an object according to the code we specify, and update the DOM when the data changes, instead of rebuilding it, which also requires that the object we specify is unique. For example, the person.age here can not be the same. Otherwise it will be an error.
If we were to introduce the by-clause to see the and track by the same time, the by is invalid. In fact, we write the grammar is not correct.
The correct syntax is this:
<div ng-repeat= "person in Peoples | Orderby:order track by person.age" >
Be sure to note that track by IS after the order by.
The effect is as follows:
By convention, we list some of the resources that might be needed:
1.http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by /
2.http://www.tuicool.com/articles/yvyjbrv
3.http://www.colabug.com/thread-1152220-1-1.html