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

fix(ngRepeat): correctly iterate over array-like objects #2554

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/ng/directive/ngRepeat.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) {
nextBlockOrder = [];


if (isArray(collection)) {
if (isArrayLike(collection)) {
collectionKeys = collection;
} else {
// if object, extract keys, sort them and use to determine order of iteration over obj props
Expand Down
2 changes: 1 addition & 1 deletion src/ng/rootScope.js
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ function $RootScopeProvider(){
oldValue = newValue;
changeDetected++;
}
} else if (isArray(newValue)) {
} else if (isArrayLike(newValue)) {
if (oldValue !== internalArray) {
// we are transitioning from something which was not an array into array.
oldValue = internalArray;
Expand Down
20 changes: 20 additions & 0 deletions test/ng/directive/ngRepeatSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,26 @@ describe('ngRepeat', function() {
});


it('should iterate over an array-like object', function() {
element = $compile(
'<ul>' +
'<li ng-repeat="item in items">{{item.name}};</li>' +
'</ul>')(scope);

document.body.innerHTML = "<p>" +
"<a name='x'>a</a>" +
"<a name='y'>b</a>" +
"<a name='x'>c</a>" +
"</p>";

var htmlCollection = document.getElementsByTagName('a');
scope.items = htmlCollection;
scope.$digest();
expect(element.find('li').length).toEqual(3);
expect(element.text()).toEqual('x;y;x;');
});


it('should iterate over on object/map', function() {
element = $compile(
'<ul>' +
Expand Down
17 changes: 17 additions & 0 deletions test/ng/rootScopeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,23 @@ describe('Scope', function() {
$rootScope.$digest();
expect(log).toEqual([ '[{},[]]' ]);
});

it('should watch array-like objects like arrays', function () {
var arrayLikelog = [];
$rootScope.$watchCollection('arrayLikeObject', function logger(obj) {
forEach(obj, function (element){
arrayLikelog.push(element.name);
})
});
document.body.innerHTML = "<p>" +
"<a name='x'>a</a>" +
"<a name='y'>b</a>" +
"</p>";

$rootScope.arrayLikeObject = document.getElementsByTagName('a')
$rootScope.$digest();
expect(arrayLikelog).toEqual(['x', 'y']);
});
});


Expand Down