简体   繁体   中英

add a class to element in ng-repeat after some event

I'm making a playlist. I have this ng-repeat where the current song is highlighted

<div ng-repeat="song in songs_list">
  <div ng-class="{'true':'current-song'}[song == current_song]">
    {{song.title}}
  </div>
</div>

now in JS I change the value of current_song . I want to apply the class current-song to the new element which is now playing currently.

On change of song set $scope.current_song to the new song and in the HTML:

<div ng-repeat="song in songs_list">
  <div ng-class="{'current-song':song===current_song}">
    {{song.title}}
  </div>
</div>

you should write like this

<div ng-repeat="song in songs_list">
 <div ng-class="{'current-song': song == current_song}">
  {{song.title}}
 </div>
</div>

Use this syntax, Try with this

<div ng-repeat="song in songs_list">
  <div ng-class="{'current-song':song.title == current_song}">
    {{song.title}}
 </div>
</div>

I suggest, use song.id instead of to song.title and keep id of current_song as song id.

The way ng-repeat works is, it creates a child scope which is prototypically inherited from current scope. Therefore inner current_song value would not update per that. I don't want to repeat answer again why it is not working, you can find explanation here . You have to use Dot Rule in order to get correct selected current_song value inside ng-repeat , & while having condition you should compare it with its unique_id (assuming you have id prop here).

$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>

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