Audio tag, how to handle it from Angular

I use HTML5 audio text, but I want to control it with Angular, in accordance with the recommendations that I do not need to touch the DOM from the controllers, so I need to create a directive.

Say I have these 2 buttons

<button onclick="playMusic()" type="button">Play Music</button> <button onclick="pauseMusic()" type="button">Pause Music</button> 

and this is in js part

 var music = document.getElementById("myMusic"); function playMusic() { music.play(); } function pauseMusic() { music.pause(); } 

but I need to write it in Angular, so how can I create a directive for it? or hoy can i implement it in the controller?

+6
source share
2 answers

In angular, any manipulation of the DOM should really be handled in directive (see the documentation ). This concerns individual issues and enhances the ability to check other angular members, such as controllers and services .

The basic directive for sound reproduction might look something like this ( fiddle ):

 app.directive('myAudio', function() { return { restrict: 'E', link: function(scope, element, attr) { var player = element.children('.player')[0]; element.children('.play').on('click', function() { player.play(); }); element.children('.pause').on('click', function() { player.pause(); }); } }; }); 

And the related HTML:

 <my-audio> <audio> <source src="demo-audio.ogg" /> <source src="demo-audio.mp3" /> </audio> <button class="play">Play Music</button> <button class="pause">Pause Music</button> </my-audio> 
+2
source

You can implement it in the controller, but you will need to do your DOM manipulation there ... what exactly are you trying to avoid.

https://docs.angularjs.org/guide/directive

http://ng-learn.org/2014/01/Dom-Manipulations/

Some relevant code that may be useful when you read the latter:

  element = angular.element('<div class="form" data-my-slide="showForm">Text</div>'); 

and here...

  link: function(scope, element, attrs) { // We dont want to abuse on watch but here it is critical to determine if the parameter has changed. scope.$watch(attrs.mySlide, function(newValue, oldValue) { // This is our logic. If parameter is true slideDown otherwise slideUp. 

Hope this helps!

+1
source

Source: https://habr.com/ru/post/985974/


All Articles