1

I'm creating a list of songs to play. I want a play/pause toggle button to the left of each song. Right now, I can't seem to get the play button to only toggle for one song within an ng-repeat. Can anyone help? The only other solution I saw that was applicable, AngularJS - using ng-show within ng-repeat, seems to have written everything the same way I did and I'm still having the same problem.

JS

$scope.play = function(id) {
  soundcloud.stream(id).then(function(player) {
    $scope.player = player;
    player.play();
    $scope.isPlaying = id;
  });
  $scope.isPlaying = id;
};

$scope.pause = function(id) {
  $scope.player.pause();
  $scope.isPlaying = false;
};

HTML

<ul ng-repeat="track in tracks">
   <li>
       <i class="fa fa-play" ng-show="isPlaying != track.id" ng-click="play(track.id)"></i>
       <i class="fa fa-pause" ng-show="isPlaying = track.id" ng-click="pause(track .id)"></i>
       <h4><a href="#" ng-bind="track.title"></a></h4>
   </li>
</ul>
Community
  • 1
  • 1
Daniel Breen
  • 179
  • 1
  • 2
  • 11

2 Answers2

1

You should probably extract the initialization of the player from the "play" function, seems like it may be unnecessary in every instance; like when you pause and play the same track.

I'm assuming you only want to play 1 track at a time, so you should assign a variable for the currently active track id, and another for whether or not a track is playing; separately.

HTML

<ul ng-repeat="track in tracks">
   <li>
       <i class="fa fa-play" ng-show="!isPlaying || activeTrack !== track.id" ng-click="play(track.id)"></i>
       <i class="fa fa-pause" ng-show="isPlaying && activeTrack === track.id" ng-click="pause()"></i>
       <h4><a href="#" ng-bind="track.title"></a></h4>
   </li>
</ul>

JavaScript

$scope.player = null;
$scope.activeTrack = null;
$scope.isPlaying = false;

$scope.play = function(id) {
  if ($scope.activeTrack === id) {
    // if this track is already active, just play it
    $scope.player.play();
    $scope.isPlaying = true;
  } else {
    // if this track isn't active, pause current player
    // then stream the new track
    if($scope.player) $scope.player.pause();

    soundcloud.stream(id).then(function(player) {
      $scope.player = player;
      $scope.player.play();
      $scope.isPlaying = true;
      $scope.activeTrack = id;
    });
  }
};

$scope.pause = function() {
  if($scope.player) $scope.player.pause();
  $scope.isPlaying = false;
};
SteamDev
  • 4,294
  • 5
  • 20
  • 29
  • Thanks. I was able to solve it by changing `ng-show="isPlaying != track.id"` to `ng-hide="isPlaying == track.id"`. I'll try out your JS though when I have more time to tinker. It looks more efficient. – Daniel Breen Jan 06 '16 at 04:12
1

As mentioned in the comment, just change this line in your HTML

<i class="fa fa-pause" ng-show="isPlaying == track.id" ng-click="pause(track .id)"></i>

the ng-show directive expects a boolean for evaluation.

Renan Ferreira
  • 2,122
  • 3
  • 21
  • 30