简体   繁体   中英

Using ng-show on ng-repeat play/pause button

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>

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

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.

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