1

只是在一個NG重複使用軌道由$指數一般性的問題,我無法找到的文檔的解決方案......

我有一個<div ng-repeat="concert in concerts track by $index">{{concert}}</div> ,在它的下面,我有一個數組,這是動態地填充音樂會的開始時間,像這樣,<p>{{startTime[$index]}}</p>。有些音樂會,但是沒有有效的開始時間,有沒有辦法找出那個[$index]的開始時間,如果沒有,定義文本取代它的位置?

我知道這是一種開放式的,&我可以用一個函數來比較concerts陣列和startTimes數組的長度,並在startTimes有數據填充剩餘的領域,但我希望有可能是一個更簡單的方法?最佳實踐?

感謝您的諮詢!

+0

不使用'$ index'完成此任務。 '$ index' *不是*數組中唯一項目的索引;相反,它是'ng-repeat'的迭代器偏移量。這意味着過濾器可能會導致'$ index'指向不同於預期的項目。 – Claies

回答

2

你可以使用一個角度過濾器,將通過並確定如果一個音樂會的開始時間,並設置一個默認值,以任何你想要的

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

或許像上面會工作。我沒有測試過它。