Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 47a2a98

Browse files
worrelIgorMinar
authored andcommitted
fix(ngRepeat): handle iteration over identical obj values
Modifies default trackByIdFn to factor both key and value into hashKey for non-array primitive (i.e. index not provided) values Closes #2787 Closes #2806
1 parent a13c01a commit 47a2a98

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/ng/directive/ngRepeat.js

+7-2
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
205205
var animate = $animator($scope, $attr);
206206
var expression = $attr.ngRepeat;
207207
var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),
208-
trackByExp, trackByExpGetter, trackByIdFn, lhs, rhs, valueIdentifier, keyIdentifier,
208+
trackByExp, trackByExpGetter, trackByIdFn, trackByIdArrayFn, trackByIdObjFn, lhs, rhs, valueIdentifier, keyIdentifier,
209209
hashFnLocals = {$id: hashKey};
210210

211211
if (!match) {
@@ -227,9 +227,12 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
227227
return trackByExpGetter($scope, hashFnLocals);
228228
};
229229
} else {
230-
trackByIdFn = function(key, value) {
230+
trackByIdArrayFn = function(key, value) {
231231
return hashKey(value);
232232
}
233+
trackByIdObjFn = function(key) {
234+
return key;
235+
}
233236
}
234237

235238
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
@@ -266,7 +269,9 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
266269

267270
if (isArrayLike(collection)) {
268271
collectionKeys = collection;
272+
trackByIdFn = trackByIdFn || trackByIdArrayFn;
269273
} else {
274+
trackByIdFn = trackByIdFn || trackByIdObjFn;
270275
// if object, extract keys, sort them and use to determine order of iteration over obj props
271276
collectionKeys = [];
272277
for (key in collection) {

test/ng/directive/ngRepeatSpec.js

+9
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,15 @@ describe('ngRepeat', function() {
8989
expect(element.text()).toEqual('misko:swe|shyam:set|');
9090
});
9191

92+
it('should iterate over an object/map with identical values', function() {
93+
element = $compile(
94+
'<ul>' +
95+
'<li ng-repeat="(key, value) in items">{{key}}:{{value}}|</li>' +
96+
'</ul>')(scope);
97+
scope.items = {age:20, wealth:20, prodname: "Bingo", dogname: "Bingo", codename: "20"};
98+
scope.$digest();
99+
expect(element.text()).toEqual('age:20|codename:20|dogname:Bingo|prodname:Bingo|wealth:20|');
100+
});
92101

93102
describe('track by', function() {
94103
it('should track using expression function', function() {

0 commit comments

Comments
 (0)