AngularJs ng-repeat에서 중복 요소 제거
나는 사전 한 권을 가지고 있는데 그 사전은 에 저장되어 있다.field_detail
<li ng-repeat = "field in field_detail">{{field.displayName}}</li>
이제 중복을 포함하지 않습니다.displayName
의field_detail
, 뭐?filter
쓸까요?
고유한 값을 가져오는 필터를 만듭니다(아마도 키로).다음과 같은 작업을 수행해야 합니다(테스트를 전혀 하지 않았기 때문에 이 일은 당신에게 맡기겠습니다.이것은 단지 아이디어를 주기 위해서입니다).
app.filter('unique', function() {
return function(collection, keyname) {
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key = item[keyname];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};
});
<div ng-repeat="item in items | unique: 'id'"></div>
주의: Array.indexOf()는 IE8에서 동작하지 않으므로 IE8을 지원하는 경우 stub in indexOf()를 사용하거나 약간 다른 방법을 사용해야 합니다.
기타 의견:이러한 라이브러리를 이미 참조하고 있는 경우는, 로우 대시 또는 언더 스코어의 고유 기능을 활용하는 필터를 작성하는 것이 좋을지도 모릅니다.
Ben Read가 제공한 답변을 바탕으로 JSFiddle을 작성했습니다.
http://jsfiddle.net/ThunderHemlock/bvsvzrr5/1/
고마워요, 벤다른 답변에서는 Angular를 사용해야 했습니다.JS UI 또는 기타 추가 프레임워크.
var app = angular.module('app', []);
app.filter('unique', function() {
return function(collection, keyname) {
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key = item[keyname];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};
});
app.controller('MyCtrl', function ($scope) {
$scope.items = [
{
id : 1,
column : "col1",
comment : "col1-label1",
text1 : "col1-label1-text1",
checked: false,
},
{
id : 2,
column : "col1",
comment : "col1-label2",
text1 : "col1-label2-text1",
checked: false,
},
{
id : 3,
column : "col2",
comment : "col2-label1",
text1 : "col2-label1-text1",
checked: false,
},
{
id : 4,
column : "col2",
comment : "col2-label2",
text1 : "col2-label2-text1",
checked: false,
},
{
id : 5,
column : "col3",
comment : "col3-label1",
text1 : "col3-label1-text1",
checked: false,
},
{
id : 6,
column : "col3",
comment : "col3-label2",
text1 : "col3-label2-text1",
checked: false,
},
{
id : 7,
column : "col4",
comment : "col4-label1",
text1 : "col4-label1-text1",
checked: false,
},
{
id : 8,
column : "col4",
comment : "col4-label2",
text1 : "col4-label2-text1",
checked: false,
}
];
});
<div ng-app="app">
<div ng-controller="MyCtrl as item">
<ul>
<li ng-repeat="item in items | unique: 'column'">
{{ item.column }}
</li>
</ul>
</div>
</div>
Ben Lesh를 피기백하기 위해 키 이름이 가짜일 경우 어레이에서 중복 개체를 삭제하는 옵션을 추가했습니다.
app.filter('unique', function () {
return function ( collection, keyname) {
var output = [],
keys = []
found = [];
if (!keyname) {
angular.forEach(collection, function (row) {
var is_found = false;
angular.forEach(found, function (foundRow) {
if (foundRow == row) {
is_found = true;
}
});
if (is_found) { return; }
found.push(row);
output.push(row);
});
}
else {
angular.forEach(collection, function (row) {
var item = row[keyname];
if (item === null || item === undefined) return;
if (keys.indexOf(item) === -1) {
keys.push(item);
output.push(row);
}
});
}
return output;
};
});
사용자가 [저장(Save)]를 클릭하면 [고유 제약 위반(Unique Constraint violation)]라고 하는 에러가 발생한다는 티켓이 표시됩니다.데이터베이스가 제한을 적용하기 전에 내 화면에 중복 항목이 표시되도록 합니다.그래서 저는 객체 배열의 모든 인스턴스를 루프하고 인스턴스 수를 세는 함수를 만들었습니다.
$scope.anyDuplicates = function () {
var dupes = false;
for (var i = 0; i < $scope.kpiList.length; i++) {
$scope.kpiList[i].cnt = 0;
for (var j = 0; j < $scope.kpiList.length; j++) {
if ($scope.kpiList[i].description == $scope.kpiList[j].description) {
$scope.kpiList[i].cnt++;
}
if ($scope.kpiList[i].cnt > 1) dupes = true;
}
}
return dupes;
}
...이 기능을 스크립트에서 사용하여 저장을 방지합니다.이 기능은 다음과 같습니다.
if ($scope.anyDuplicates()) {
alert('Duplicates Detected. Please remove the duplicates before pressing the save button.');
} else {
save();
}
...새 레코드를 추가하는 즉시 사용자에게 다음과 같이 표시합니다.
$scope.kpiList.push({kpiId: newId, description: newDescription, new: true});
$scope.anyDuplicates();
...그리고 내 HTML에서 복제품이 어디에 있는지 사용자에게 알려줄 것이 있다...
<tr ng-repeat="row in kpiList | filter:searchText | orderBy:['kpiTypeId', 'description'] ">
<td>
<span
ng-show="row.cnt > 1"
style="color: red; font-size: xx-small">
duplicate
</span>
</td>
...
</tr>
네, 각 인스턴스를 의도적으로 비교하고 있습니다.그래야 암호가 적어지니까> 0 이 아닌 .cnt > 1 인지를 확인합니다.
그리고 주의할 점은...kpiList.cnt 필드는 함수를 처음 실행할 때까지 존재하지 않습니다.ng-show="row.cnt > 1"은 false(truthy가 아님)를 나타내며 row.cnt가 값을 가질 때까지 표시되지 않습니다.
또한 스팬을 스타일 속성에 넣는 대신 스타일시트를 사용하여 포맷해야 합니다.
사용자 고유의 기능을 만듭니다.
productArray =[];
angular.forEach($scope.leadDetail, function(value,key){
var index = $scope.productArray.indexOf(value.Product);
if(index === -1)
{
$scope.productArray.push(value.Product);
}
});
언급URL : https://stackoverflow.com/questions/20222555/angularjs-remove-duplicate-elements-in-ng-repeat
'source' 카테고리의 다른 글
스프링 부트를 사용한 Maven 리소스 필터링: 자리 표시자를 확인할 수 없습니다. (0) | 2023.02.23 |
---|---|
"매직 따옴표"가 비활성화되어 있는데, 왜 PHP/WordPress는 계속해서 내 POST 데이터를 자동 이스케이프합니까? (0) | 2023.02.23 |
Mongoose Schema가 모델에 등록되지 않았습니다. (0) | 2023.02.23 |
node.js와 함께 기본 Ajax 송수신 (0) | 2023.02.23 |
실험 구문 'jsx'에 대한 지원이 현재 사용되도록 설정되지 않았습니다. (0) | 2023.02.23 |