Rohit
Rohit

Reputation: 221

audio tag of HTML 5 is not working on continuous usage in angularJS

<audio id="myaudio" class="hide"> HTML5 audio </audio>
<button id="btn" ng-click="playAudio()">Click</button>


 $scope.playAudio = function(){
    var oAudio = document.getElementById('myaudio');
    oAudio.src = audiofile;
    oAudio.load();
    oAudio.play();
 }

I have used the above code. Now this code is not working on continuous usage, like if we click 10-12 times this will not work.

Upvotes: 0

Views: 99

Answers (1)

Joe Hany
Joe Hany

Reputation: 1015

It is bad practice to access DOM from the controller. You should use a directive to do this job.

I am using something like this:

yourApp.directive('audioPlayer', function () {
return {
  restrict: 'E',
  scope: {
    src: '=src'
  },
  link: function (scope, element) {
    var audioElement = document.createElement('audio');
    audioElement.src = scope.src;
    audioElement.controls = 'controls';
    element.html(audioElement);
  }
};

});

and in the HTML:

<audio-player src="scope.audio"></audio-player>

Upvotes: 3

Related Questions