Ng-repeat, for-loop and push

I'm crazy. What is wrong this hi-mundane example? I am trying to just check out some basic things with angularjs 1.5.5.

HTML:

<div ng-app="myApp" ng-controller="Ctrl"> <h3>test 1:</h3> <span ng-repeat="label in test(1)">{{label}}</span> <h3>test 2:</h3> <span ng-repeat="label in test(2)">{{label}}</span> </div> 

JS:

 angular.module('myApp', []) .controller('Ctrl', ['$scope', function ($scope) { $scope.test = function(amount) { var result = []; result.push("1"); for (var i = 0; i < amount; i++) { result.push("2"); } result.push("3"); return result; } }]); 

JsFiddle: http://jsfiddle.net/d3v6vq7w/7/

Nice, the loop works with 1 iteration, but not with Example 2. Nothing is printed. What gives?

+5
source share
3 answers

You have duplicates in the returned array. Adding track by $index will solve your problem.

 <span ng-repeat="label in test(2) track by $index">{{label}}</span> 

Fiddle - http://jsfiddle.net/ayay0d6u/

+4
source

If you look at the error message, you will get a response.

Error: ngRepeat: dupes Duplicate key in the repeater Duplicates in the repeater are not allowed. Use the expression 'track by' to specify unique keys. Repeater: label in test (2), duplicate key: line: 2, duplicate value: 2

On the error page

Duplicate keys are prohibited because AngularJS uses keys to bind DOM nodes to elements.

+3
source

This is because duplicates in the repeater are not allowed. To resolve this problem, use the expression "track by".

In your example, test2 returns [1,2,2,3], which has a duplicate element.

The above example can be solved using the track at $ index.

You can refer to angular js documentation: https://docs.angularjs.org/error/ngRepeat/dupes

+1
source

Source: https://habr.com/ru/post/1247425/


All Articles