Skip to content

Commit 074debb

Browse files
committed
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 Close angular#2787
1 parent b8ea7f6 commit 074debb

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/ng/directive/ngRepeat.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,16 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
175175
return trackByExpGetter($scope, hashFnLocals);
176176
};
177177
} else {
178-
trackByIdFn = function(key, value) {
179-
return hashKey(value);
178+
trackByIdFn = function(key, value, index) {
179+
var valType = typeof value;
180+
181+
// if value is a primitive and key != index (case for arrays)
182+
// then append key to value to ensure uniqueness for identical values
183+
if(valType != 'object' && !(typeof key === 'number' || key === index)) {
184+
return hashKey(key + ':' + value);
185+
} else {
186+
return hashKey(value);
187+
}
180188
}
181189
}
182190

test/ng/directive/ngRepeatSpec.js

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

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

8998
describe('track by', function() {
9099
it('should track using expression function', function() {

0 commit comments

Comments
 (0)