[英]add a class to element in ng-repeat after some event
我正在制作播放列表。 我有這個ng-repeat,其中突出顯示了當前歌曲
<div ng-repeat="song in songs_list">
<div ng-class="{'true':'current-song'}[song == current_song]">
{{song.title}}
</div>
</div>
現在在JS中,我更改current_song
的值。 我想將current-song
類應用於current-song
正在播放的新元素。
更改歌曲后,將$ scope.current_song設置為新歌曲並在HTML中:
<div ng-repeat="song in songs_list">
<div ng-class="{'current-song':song===current_song}">
{{song.title}}
</div>
</div>
你應該這樣寫
<div ng-repeat="song in songs_list">
<div ng-class="{'current-song': song == current_song}">
{{song.title}}
</div>
</div>
使用此語法,嘗試與此
<div ng-repeat="song in songs_list">
<div ng-class="{'current-song':song.title == current_song}">
{{song.title}}
</div>
</div>
我建議,使用song.id
而不是song.title
,並將current_song的ID保留為歌曲ID。
ng-repeat
工作方式是,創建一個子作用域,該子作用域通常是從當前作用域繼承的。 因此,內部current_song
值將不會current_song
更新。 我不想再回答一次,為什么它不起作用,您可以在這里找到解釋 。 您必須使用Dot Rule
才能在ng-repeat
內獲取正確的選定current_song
值,並且在有條件的情況下,應將其與其unique_id進行比較(假設此處具有id
屬性)。
$scope.model = {
current_song: null
};
的HTML
<div ng-repeat="song in songs_list">
<div ng-class="{'current-song': song.id == model.current_song.id}">
{{song.title}}
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.