Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Audio tag, how to handle it from Angular

I am using the HTML5 audio tag, but I want to control it from Angular, according to the guidelines I don't have to touch the DOM from the Controllers so I have to create a Directive.

Let's say I have this 2 buttons

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

and this in the JS part

var music = document.getElementById("myMusic"); 

function playMusic() { 
    music.play(); 
} 

function pauseMusic() { 
    music.pause(); 
} 

but I need to transcript that into Angular, so, how can I create a directive for that ? or hoy can I implement it in a Controller ?

like image 862
Non Avatar asked Apr 25 '15 23:04

Non


2 Answers

In angular, any DOM manipulation should really be handled in a directive (see documentation). This is to separate concerns and to improve the testability of other angular actors such as controllers and services.

A basic directive to play audio 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 associated 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>
like image 96
net.uk.sweet Avatar answered Oct 20 '22 16:10

net.uk.sweet


You can implement it in the controller, but you'd need to perform your DOM manipulations in there...which is exactly what you're trying to avoid.

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

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

Some relevant code, which might be useful to look out for while you read the last one:

    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 that helps!

like image 33
Sze-Hung Daniel Tsui Avatar answered Oct 20 '22 15:10

Sze-Hung Daniel Tsui