1

I'm trying to loop through a JSON object using ng-repeat, using this as reference. What I currently have is:

<mat-card-content>
  <p>{{ selected.items }}</p>
  <p>{{ selected.items["0aa60412-a62b-4967-8c9e-b12764df6a9d"].itemName }}</p>
  <ul>
    <li ng-repeat="item in selected.items">{{ item.itemName }}</li>
  </ul>
</mat-card-content>

where the 2nd <p> uses a hardcoded ID of the first entry being returned

The <p> tags work, but the <li> does not, it just has a single bullet with no content in it (where the object has 16 items). The console gives the error TypeError: Cannot read property 'itemName' of undefined.

The JSON object is formatted like so:

{
  "0aa60412-a62b-4967-8c9e-b12764df6a9d": { itemName: "value", [...] },
  [...]
}

Other attempts which also failed include:

<li ng-repeat="(key, value) in selected.items">{{ key }}</li>

What am I doing wrong here?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
David Starkey
  • 1,840
  • 3
  • 32
  • 48
  • Possible duplicate of https://stackoverflow.com/questions/15127834/how-to-iterate-over-the-keys-and-values-with-ng-repeat-in-angularjs – Frank Modica Dec 07 '18 at 16:11
  • @FrankModica Tried the answer for that question, didn't work. Should have mentioned that I tried all the methods in the ngRepeat reference material linked in the question. – David Starkey Dec 07 '18 at 16:15
  • Not even if you do `{{ value.itemName }}`? – Frank Modica Dec 07 '18 at 16:18
  • @FrankModica Correct. Seeing [this comment](https://stackoverflow.com/questions/15127834/how-to-iterate-over-the-keys-and-values-with-ng-repeat-in-angularjs#comment33941787_15127934) I might just re-work this to be an array and figure out a different way to loop over it. – David Starkey Dec 07 '18 at 16:20
  • Can't reproduce. Please give a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Blackhole Dec 07 '18 at 16:23
  • @Blackhole This was a problem with my lack of experience with Angular. I've posted an answer to hopefully help others that fall into the same confusions. – David Starkey Dec 07 '18 at 16:49

1 Answers1

0

This seems to be an issue with my being new to Angular. Basically, ngRepeat is not recommended for this. Also, ng-repeat a feature of AngularJS but not Angular, which are apparently different things. With that out of the way, onto the solution.

Since you cannot use ng-repeat, the alternative is to change your object to an array and use *ngFor like so:

<li *ngFor="let item of selected.items">{{ item.itemName }}</li>

For converting from object to array, see this answer:

return Object.keys(retItems).map(function(idx) {
  return retItems[idx];
});
David Starkey
  • 1,840
  • 3
  • 32
  • 48