0
<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.

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.