Why does ng-repeat treat this array like a string?


#1

With a regular array in my controller:

$scope.results = ["file1","file2","file3","file4"];

Doing console.log($scope.results) outputs:

["file1","file2","file3","file4"]

My HTML:

<ul>
  <li ng-repeat="result in results" type="item-text-wrap">
    <div><img ng-src="{{result}}"/></div>
  </li>
</ul>

Throws the error:

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys.

If I add track by $index

<ul>
  <li ng-repeat="result in results track by $index" type="item-text-wrap">
    <div><img ng-src="{{result}}"/></div>
  </li>
</ul>

Each character is treated as an item…

<div><img ng-src="%22"/></div>
<div><img ng-src="f"/></div>
<div><img ng-src="i"/></div>
<div><img ng-src="l"/></div>
<div><img ng-src="e"/></div>
<div><img ng-src="1"/></div>
<div><img ng-src="%22"/></div>
etc...

What am I doing wrong?

Thanks!


#2

I assume your results is actually the same as your $scope.files = ["file1","file2","file3","file4"]; ?

Try making it like this:

$scope.results= [{filename:"file1"},{filename:"file2"},{filename:"file3"},{filename:"file4"}];

Angular requires an array of objects, because it will expose the object with it’s params in the scope… If I recall correctly that is!

The template should then be like this:

<ul>
  <li ng-repeat="result in results" type="item-text-wrap">
    <div><img ng-src="{{result.filename}}"/></div>
  </li>
</ul>

#3

Thanks!

(Yes, results is files. Just a demo typo.)


#4

Your welcome :smile:

Your issue was resolved now?


#5

Yes, thank you…