AngularJS ng-repeat array has repeated value solution, angularjsng-repeat

Source: Internet
Author: User

AngularJS ng-repeat array has repeated value solution, angularjsng-repeat

Preface

As you all knowng-repeatEveryitemMust be unique. OtherwiseconsoleTheerrorTell you whichkey/valueIs repeated.

For example:

$scope.items = [ 'red', 'blue', 'yellow', 'white', 'blue'];

This arrayblueRepeat it. html traverses it like this.

<li ng-repeat="item in items">{{ item }}</li>

The console will throw an error:

Click the error link to the Angular official website to see the detailed error. The official website clearly states that the error is due to repeated values:

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in items, Duplicate key: string:blue, Duplicate value: blue

Solution

This is confusing. It is normal for an array to have duplicate values in a normal business, and the array must be unique.ng-repeatIn order to traverse it, I went on to look down and found that the official website provided a solution.

<div ng-repeat="value in [4, 4] track by $index"></div>

So I changed it according to this solution.

<li ng-repeat="item in items track by $index">{{ item }}</li>

Refresh the webpage and the content is parsed properly

Actuallyng-repeatYou still need a uniquekeyBut you don'ttrackThe default value isitemIn addition, this problem occurs only when the string or number of the common data type is changedObject

$scope.items = [ ['red'], ['blue'], ['yellow'], ['white'], ['blue']];

Html is restored

<li ng-repeat="item in items">{{ item }}</li>

Execution result:

If you don't understand, take a look at the following arithmetic expression, guess what the result is, and try your answer on the browser console.

[] === []

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

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.