programing

Angular ng-repeat 오류 "반복기에서 중복이 허용되지 않습니다."

cafebook 2023. 4. 28. 21:31
반응형

Angular ng-repeat 오류 "반복기에서 중복이 허용되지 않습니다."

사용자 정의 필터를 다음과 같이 정의합니다.

<div class="idea item" ng-repeat="item in items" isoatom>    
    <div class="section comment clearfix" ng-repeat="comment in item.comments | range:1:2">
        ....
    </div>
</div>

필터가 사용 중인 ng-repeat이 다른 ng-repeat 내에 중첩되어 있는 것을 볼 수 있습니다.

필터는 다음과 같이 정의됩니다.

myapp.filter('range', function() {
    return function(input, min, max) {
        min = parseInt(min); //Make string input int
        max = parseInt(max);
        for (var i=min; i<max; i++)
            input.push(i);
        return input;
    };
});

다음과 같은 정보:

오류: 반복기에서는 중복이 허용되지 않습니다.리피터: item.comment | 범위:1:2 ngRepeatAction@https://ajax.googleapis.com/ajax/libs/angularjs/1.1.4/an

솔루션에 대한 설명은 http://www.anujgakhar.com/2013/06/15/duplicates-in-a-repeater-are-not-allowed-in-angularjs/ 에서 확인할 수 있습니다.

AngularJS는 ng-repeat 디렉티브에서 중복을 허용하지 않습니다.즉, 다음을 수행하려고 하면 오류가 발생합니다.

// This code throws the error "Duplicates in a repeater are not allowed.
// Repeater: row in [1,1,1] key: number:1"
<div ng-repeat="row in [1,1,1]">

그러나 아래와 같이 고유성을 결정하는 색인을 정의하기 위해 위의 코드를 약간 변경하면 다시 작동합니다.

// This will work
<div ng-repeat="row in [1,1,1] track by $index">

공식 문서는 다음과 같습니다. https://docs.angularjs.org/error/ngRepeat/dupes

JSON이 예상되지만 여전히 동일한 오류가 발생하는 경우 데이터를 구문 분석해야 합니다.

$scope.customers = JSON.parse(data)

프로젝트에서 $index에 의한 ng-repeat track을 사용하고 있었는데 데이터베이스에서 데이터가 왔을 때 제품이 반영되지 않는 문제가 있었습니다.내 코드는 다음과 같습니다.

<div ng-repeat="product in productList.productList track by $index">
  <product info="product"></product>
 </div>

위 코드에서 제품은 제품을 표시하기 위한 별도의 지침입니다.하지만 우리가 범위에서 데이터를 전달할 때 $index가 문제를 일으킨다는 것을 알게 되었습니다.따라서 데이터 손실 및 DOM은 업데이트할 수 없습니다.

저는 product.id 을 아래와 같은 키워드로 사용하여 솔루션을 찾았습니다.

<div ng-repeat="product in productList.productList track by product.id">
  <product info="product"></product>
 </div>

그러나 두 개 이상의 제품이 동일한 ID로 제공되면 위의 코드가 다시 실패하고 다음 오류가 발생합니다.

angular.js:11706 오류: [ngRepeat:dupes] 리피터에서 중복이 허용되지 않습니다.고유 키를 지정하려면 'track by' 식을 사용합니다.리피터

그래서 마지막으로 아래와 같이 ng-repeat의 동적 고유 키를 만들어 문제를 해결했습니다.

<div ng-repeat="product in productList.productList track by (product.id + $index)">
  <product info="product"></product>
 </div>

이것은 나의 문제를 해결했고 이것이 앞으로 당신에게 도움이 되기를 바랍니다.

"범위" 필터는 어떻게 할 예정입니까?

다음은 당신이 시도하고 있는 작업 샘플입니다: http://jsfiddle.net/evictor/hz4Ep/

HTML:

<div ng-app="manyminds" ng-controller="MainCtrl">
  <div class="idea item" ng-repeat="item in items" isoatom>    
    Item {{$index}}
    <div class="section comment clearfix" ng-repeat="comment in item.comments | range:1:2">
      Comment {{$index}}
      {{comment}}
    </div>
  </div>
</div>

JS:

angular.module('manyminds', [], function() {}).filter('range', function() {
    return function(input, min, max) {
        var range = [];
        min = parseInt(min); //Make string input int
        max = parseInt(max);
        for (var i=min; i<=max; i++)
            input[i] && range.push(input[i]);
        return range;
    };
});

function MainCtrl($scope)
{
    $scope.items = [
        {
            comments: [
                'comment 0 in item 0',
                'comment 1 in item 0'
            ]
        },
        {
            comments: [
                'comment 0 in item 1',
                'comment 1 in item 1',
                'comment 2 in item 1',
                'comment 3 in item 1'
            ]
        }
    ];
}

쉐어포인트 2010으로 작업할 때 이 오류가 발생하는 경우: .json 파일 확장명을 변경하고 restService 경로를 업데이트하십시오.추가 "$index별 추적"이 필요하지 않았습니다.

운 좋게도 저는 이 링크를 다음과 같은 근거로 전달했습니다.

.json은 SP2010에서 중요한 파일 형식이 됩니다.SP2010에는 특정 웹 서비스 끝점이 포함되어 있습니다.이러한 파일의 위치는 14hive\isapi 폴더입니다.이 파일들의 확장자는 .json입니다.그것이 그것이 그러한 오류를 주는 이유입니다.

"json 파일 확장자가 아닌 json 파일의 내용만 확인"

파일 확장명이 변경되면 이 모두 설정되어야 합니다.

만약 다른 사람에게 이런 일이 생길 경우를 대비하여 여기서 이를 문서화하고 있는데, 실수로 ng-model을 ng-repeat 배열과 동일하게 설정했기 때문에 이 오류가 발생했습니다.

 <select ng-model="list_views">
     <option ng-selected="{{view == config.list_view}}"
         ng-repeat="view in list_views"
         value="{{view}}">
         {{view}}
     </option>
 </select>

다음 대신:

<select ng-model="config.list_view">
     <option ng-selected="{{view == config.list_view}}"
         ng-repeat="view in list_views"
         value="{{view}}">
         {{view}}
     </option>
 </select>

배열을 확인해보니 중복된 내용이 없어서 변수만 다시 확인해주세요.

반복기에서는 중복이 허용되지 않습니다.고유 키를 지정하려면 'track by' 식을 사용합니다.

Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="angular.js"></script>

</head>
<body>
    <div ng-app="myApp" ng-controller="personController">
        <table>
            <tr> <th>First Name</th> <th>Last Name</th> </tr>
            <tr ng-repeat="person in people track by $index">
                <td>{{person.firstName}}</td>
                <td>{{person.lastName}}</td>
                <td><input type="button" value="Select" ng-click="showDetails($index)" /></td>
            </tr>

        </table> <hr />
        <table>
            <tr ng-repeat="person1 in items track by $index">
                <td>{{person1.firstName}}</td>
                <td>{{person1.lastName}}</td>
            </tr>
        </table>
        <span>   {{sayHello()}}</span>
    </div>
    <script> var myApp = angular.module("myApp", []);
        myApp.controller("personController", ['$scope', function ($scope)
        { 
            $scope.people = [{ firstName: "F1", lastName: "L1" },
                { firstName: "F2", lastName: "L2" }, 
                { firstName: "F3", lastName: "L3" }, 
                { firstName: "F4", lastName: "L4" }, 
                { firstName: "F5", lastName: "L5" }]
            $scope.items = [];
            $scope.selectedPerson = $scope.people[0];
            $scope.showDetails = function (ind) 
            { 
                $scope.selectedPerson = $scope.people[ind];
                $scope.items.push($scope.selectedPerson);
            }
            $scope.sayHello = function ()
            {
                return $scope.items.firstName;
            }
        }]) </script>
</body>
</html>

<ul> 태그 내에서 ang-repeat을 호출하면 중복을 허용할 수 있습니다.이 링크를 참조하십시오.ToDo2.html 참조

반복기에서는 중복이 허용되지 않습니다.고유 키를 지정하려면 'track by' 식을 사용합니다.반복기: mydt의 sdetail, 중복 키: 문자열: , 중복 값:

제 php api 파트에 데이터베이스 이름을 잘못 적었기 때문에 이 오류가 발생했습니다...

따라서 이 오류는 사용자가 이름을 잘못 쓴 데이터베이스에서 데이터를 가져올 때도 발생할 수 있습니다.

나의JSON응답은 다음과 같았습니다.

{
    "items":  [
        {
            "index": 1, "name": "Samantha", "rarity": "Scarborough","email": "maureen@sykes.mk"
        },{ 
            "index": 2, "name": "Amanda", "rarity": "Vick", "email": "jessica@livingston.mv"
        }
    ]
}

그래서 제가.ng-repeat = "item in variables.items"표시합니다.

언급URL : https://stackoverflow.com/questions/16296670/angular-ng-repeat-error-duplicates-in-a-repeater-are-not-allowed

반응형