【问题标题】:General angular ng-repeat and track by $index一般角度 ng-repeat 和跟踪 $index
【发布时间】:2015-12-08 21:49:03
【问题描述】:

只是一个关于在 ng-repeat 中使用 track by $index 的一般问题,我在文档中找不到解决方案...

我有一个<div ng-repeat="concert in concerts track by $index">{{concert}}</div>,在它下面,我有一个数组,动态填充音乐会的开始时间,就像这样,<p>{{startTime[$index]}}</p>。有些音乐会没有有效的开始时间,有没有办法确定 [$index] 是否有 startTime,如果没有,定义代替它的文本?

我知道这是一种开放式,我可以使用函数来比较 concerts 数组和 startTimes 数组的长度,并用数据填充 startTimes 中的其余字段,但我希望有可能是更简单的方法?最佳做法?

感谢您的建议!

【问题讨论】:

  • 请勿使用$index 执行此任务。 $index不是数组中唯一项的索引;相反,它是ng-repeat 的迭代器偏移量。这意味着过滤器可能会导致 $index 指向与预期不同的项目。

标签: javascript angularjs angularjs-ng-repeat ng-repeat angularjs-track-by


【解决方案1】:

您可以使用一个角度过滤器,该过滤器将通过并确定音乐会是否有开始时间,并将默认值设置为您想要的任何值

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;
  };
});

也许像上面这样的东西会起作用。我没有测试过。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2014-12-31
    相关资源
    最近更新 更多