简体   繁体   中英

General angular ng-repeat and track by $index

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM