Skip to content

Commit

Permalink
fix(ngRepeat): handle iteration over identical obj values
Browse files Browse the repository at this point in the history
Modifies default trackByIdFn to factor both key and value into hashKey
for non-array primitive (i.e. index not provided) values

Closes angular#2787
Closes angular#2806
  • Loading branch information
worrel authored and IgorMinar committed Jul 24, 2013
1 parent a13c01a commit 47a2a98
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/ng/directive/ngRepeat.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
var animate = $animator($scope, $attr);
var expression = $attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),
trackByExp, trackByExpGetter, trackByIdFn, lhs, rhs, valueIdentifier, keyIdentifier,
trackByExp, trackByExpGetter, trackByIdFn, trackByIdArrayFn, trackByIdObjFn, lhs, rhs, valueIdentifier, keyIdentifier,
hashFnLocals = {$id: hashKey};

if (!match) {
Expand All @@ -227,9 +227,12 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
return trackByExpGetter($scope, hashFnLocals);
};
} else {
trackByIdFn = function(key, value) {
trackByIdArrayFn = function(key, value) {
return hashKey(value);
}
trackByIdObjFn = function(key) {
return key;
}
}

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

if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdFn || trackByIdArrayFn;
} else {
trackByIdFn = trackByIdFn || trackByIdObjFn;
// if object, extract keys, sort them and use to determine order of iteration over obj props
collectionKeys = [];
for (key in collection) {
Expand Down
9 changes: 9 additions & 0 deletions test/ng/directive/ngRepeatSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ describe('ngRepeat', function() {
expect(element.text()).toEqual('misko:swe|shyam:set|');
});

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

describe('track by', function() {
it('should track using expression function', function() {
Expand Down

0 comments on commit 47a2a98

Please sign in to comment.