A solution to Angularjs ng-repeat array with duplicate values _angularjs

Source: Internet
Author: User

Objective

Everyone knows that by default ng-repeat , each one item is guaranteed to be unique, or console it will be played to error tell you which key/value is repeated.

Such as:

$scope. Items = [
 ' red ',
 ' Blue ',
 ' yellow ', ' white
 ',
 ' Blue '
];

The array blue repeats, so the HTML traverses it.

<li ng-repeat= "Item in Items" >{{Item}}</li>

The console throws an error:

Click the error link to angular website to see detailed errors, the official website is clearly given because the value is repeated:

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

Solving method

This is confused, normal business in the array has a duplicate value is very normal, the array to be hard to make the only ng-repeat way to traverse the white blind, continue to look down, found that the official website to a solution

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

So I changed it according to the plan.

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

Refresh the page and the content is parsed correctly

In fact, ng-repeat still need a unique key , but you do not track say the default is item itself, but also only in ordinary data type strings, numbers and so will appear this problem, if replaced byObject

$scope. Items = [
 [' Red '], [' Blue '], ['
 Yellow '], [' White
 '],
 [' Blue '
]];

HTML revert to

<li ng-repeat= "Item in Items" >{{Item}}</li>

Execution results:

Do not understand the children's shoes then look at the following operational expressions, guess what the results are, and then in the browser console to try your answer is correct

[] === []

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

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.