Use the track by sub-statement in the AngularJS ng-repeat command to solve the problem of repeated data traversal errors. angularjsng-repeat

Source: Internet
Author: User

Use the track by sub-statement in the AngularJS ng-repeat command to solve the problem of repeated data traversal errors. angularjsng-repeat

This article describes how to use the track by substatement in the AngularJS ng-repeat command to solve the problem of repeated data traversal errors. We will share this with you for your reference. The details are as follows:

We can use the ng-repeat command to traverse a JavaScript array. When the array contains duplicate elements, AngularJS reports an error:

Error: [ngRepeat: dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: number: 1. The following code returns an error:

This is because ng-Repeat does not allow two objects with the same Id in the collection.

For example: item in items is equivalent to item in items track by $ id (item). This implies that the DOM elements will be associated by item identity in the array.

For basic data types such as numbers or strings, its id is its own value. Therefore, two identical numbers are not allowed in the array. To avoid this error, You need to define your own track by expression.

// Generate a unique id on the business
Item in items track by item. id
// Or use the loop index variable $ index directly.
Item in items track by $ index

For javascript Object Data, ng-repeat does not consider the same object even if the content is the same. If you use dataList in the above Code, no error will be reported. For example, $ scope. dataList = [{"age": 10 },{ "age": 10}];

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.