1

Just a general question about using track by $index in an ng-repeat, I couldn't find a solution in the docs...

I have a <div ng-repeat="concert in concerts track by $index">{{concert}}</div>, below it, I have an array, that is dynamically populated with the concert's start time like this, <p>{{startTime[$index]}}</p>. Some concerts, however do not have a valid start time, is there a way to figure out if there is a startTime for that [$index] and if not, define the text that takes its place?

I know this is kind of open ended, & I could use a function to compare the length of concerts array and startTimes array, and populate the remaining fields in startTimes with data, but I was hoping there may be an easier way? Best practice?

Thanks for your advice!

Quade Dumont
  • 175
  • 9
  • don't use `$index` for this task. `$index` *is not* the index of the unique item in an array; instead, it is the iterator offset for `ng-repeat`. This means that filters can cause the `$index` to point to a different item than expected. – Claies Dec 08 '15 at 22:04

1 Answers1

2

you could use an angular filter that will go through and identify if a concert has a start time and set a default value to whatever you want

https://docs.angularjs.org/api/ng/filter/filter

app.filter('startingTimeExists', () => {
  return (collection) => {
    let filtered = [];
    angular.forEach(collection, (concert) =>{
      if(concert.hasOwnProperty('startingTime')){
        filtered.push(concert);
      } else {
        concert.startingTime = "7:00PM"
        filtered.push(concert)
      }
    })
    return filtered;
  };
});

perhaps something like the above will work. I haven't tested it.

Darien Lombardi
  • 105
  • 1
  • 7