0

I built an Angular app and I am using ng-repeat to show data from the model in to an html view. But i am getting wrong values:

Model looks like this:

[{
   id : 1,
   name : 'jijo'
   address : 'addressone',
 },
 {
   id : 2,
   name : 'albert'
   address : 'addressone',
 },

{
   id : 3,
   name : 'moana'
   address : 'addressone',
 },
{
   id : 4,
   name : 'card'
   address : 'addressone',
 }
]

Html code looks like this:

    <section id="main" ng-repeat="(id, name) in data.repo track by id"
    <div id="sub_main_one">
       {{id}} //prints one
     </div>

    <div id="sub_main_two">
       {{id}} //prints one
     </div>

     <div id="sub_main_three">
       {{id}} //prints one
     </div>

     <div id="sub_main_four">
       {{id}} //prints one
     </div>    


     <div id="sub_main_five">
       {{id}} //suppose to be one but prints 4 on the first repeat
     </div>

   </section> 

The id is printing 1 in most of the divs, but in the last div it's giving me a wrong value (4), which is the id from the last object in the array. How can I fix this issue ?..

Jijo John
  • 1,375
  • 9
  • 21

1 Answers1

1

There is a lot of missing > in your code, then your ng-repeat sentence is wrong, the (key, value) in obj sintax is to iterate on properties of an object, not to iterate items on an array (check the angularjs documentation):

Fixing that:

<section id="main" ng-repeat="item in data">
  <div id="sub_main_one">
     {{item.id}}
     hey
   </div>
  <div id="sub_main_two">
     {{id}}
   </div>
   <div id="sub_main_three">
     {{id}}
   </div>
   <div id="sub_main_four">
     {{id}}
   </div>
   <div id="sub_main_five">
     {{id}}
   </div>
 </section> 

here is the plunker

Javier Gonzalez
  • 915
  • 6
  • 14
  • Good Plunk ! (what the OP should have done in the first place) Btw, does he even need the `track by`? And, if so, why not `track by $index`? – Mawg says reinstate Monica Feb 01 '18 at 20:02
  • he doesn't need the `track by`, that's only to deal with duplicated items, check https://stackoverflow.com/questions/39640160/what-is-track-by-in-angularjs-and-how-does-it-work – Javier Gonzalez Feb 01 '18 at 20:06