2017-06-02 132 views
0

我目前正在試圖爲音樂家制作一個網站,他希望在網站上有他的專輯歌曲的小預覽。AngularJS:播放/靜音按鈕上的音頻預覽

我現在有一個JSON陣列的歌曲,我加載到AngularJS並加載到頁面

<tr ng-repeat="song in info.songs"> 
     <td> 
      <a href="" ng-click='startPlayback(song.url)' class="play-symbol"><span class="glyphicon glyphicon-headphones" aria-hidden="true"></a> 
      <a href="" ng-click='stopPlayback()' class="stop-symbol"><span class="glyphicon glyphicon-volume-off" aria-hidden="true"></a> 
     </td> 
     <td>{{song.title}}</td> 
     ... 
</tr> 

正如你可以看到我還創建了一個「startPlayback」和「stopPlayback」的名字,其正是它所說的。

我現在的問題是,我只想在開始時顯示「glyphicon-headphones」符號,當我開始播放時,只有在開始播放歌曲時,耳機會變爲「glyphicon-volume-off」符號。 我已經得到了這個,但現在我遇到了問題:

我想要它,以便您現在可以單擊任何其他耳機(「開始」)圖標,播放停止播放(我也已經得到),播放的「舊」歌曲的靜音符號變回耳機,「新」符號變爲靜音符號。

你會如何實現這樣的目標?

回答

2

我認爲你可以使用ngClass directive動態切換css類使用當前正在播放的歌曲的狀態。 不知道你在控制器中的代碼如何, ,但希望我的想法能幫助你。因此,對於標記,你可以使用類似(這是一個good practice to use track by for repeaters and one time bindings如果你關心性能):

<tr ng-repeat="song in info.songs track by song.id"> 
     <td> 
      <a href="javascript:void(0)" ng-click='togglePlayback(song, info.songs)' class="play-symbol" ng-class="{'play-symbol' : !song.isPlaying, 'stop-symbol': song.isPlaying}"> 
      <span class="glyphicon" aria-hidden="true" ng-class="{'glyphicon-headphones' : !song.isPlaying, 'glyphicon-volume-off': song.isPlaying}"></span> 
      </a> 
     </td> 
     <td>{{::song.title}}</td> 
     ... 
</tr> 

並在控制器,你可以將切換被點擊歌曲的狀態的方法:

$scope.togglePlayback = function(song, songs){ 
    //set "stopped" css class for all songs except the one was clicked 
    angular.forEach(songs, function(s){ 
     if (s.id != song.id) { 
      s.isPlaying = false; 
     } 
    }); 

    //toggle the song was clicked 
    song.isPlaying = !song.isPlaying; 

    //some you code to start/stop playback depending on the song.isPlaying value 
    //... 

} 

希望這會幫助你。