Garrett Garrett - 3 months ago 40
HTML Question

How to do a jQuery play and stop toggle button in Angular?

Recently I created this jQuery play and pause button (http://jsfiddle.net/jTh3v/338/) which allows the user to toggle between play and pause when playing the music. I want to recreate this functionality but in AngularJS. However I'm very junior when it comes to Angular and struggled to do so. In the JSFiddle I hide the audio tag because I don't want the user to be able to see it, instead I just have 2 icons that allows them to play/pause the music. Could someone please help?

jQuery - toggles between the 2 icons and plays/pauses the song:

$('#button_play').on('click', function() {
$('#button_pause').show();
$('#button_play').hide();
$('#aud').trigger('play');
});
$('#button_pause').on('click', function() {
$('#button_play').show();
$('#button_pause').hide();
$('#aud').trigger('pause');
});


HTML:

<div id="soundTag"></div><br>

<div>
<button id="button_play" class="first" ng-click="" type="button">
<i class="glyphicon glyphicon-volume-up"></i></button>
<button id="button_pause" class="second" ng-click="" type="button">
<i class="glyphicon glyphicon-volume-off"></i></button>
</div>

Answer

You should do like so :

<div id="soundTag"></div><br>

  <div>
    <button ng-show="!playing" id="button_play" class="first" ng-click="play()" type="button">
      <i class="glyphicon glyphicon-volume-up"></i></button>
    <button ng-show="playing" id="button_pause" class="second" ng-click="pause()" type="button">
      <i class="glyphicon glyphicon-volume-off"></i></button>
  </div>

In your JS

      $scope.play = function () {
        $scope.playing = true;
        angular.element(document.querySelector('#aud'))[0].play(); 
        // or document.querySelector('#aud').play();
      };
      $scope.pause = function () {
        $scope.playing = false;
        angular.element(document.querySelector('#aud'))[0].pause();
        // or document.querySelector('#aud').pause();
      };
Comments