Creating a new directive using AngularJS using an HTML5 audio element

I am new to angular and I created sound buttons using the angular directive:

app.directive('soundButton', [function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var audioSrc = attrs.origem;
            var audio = new Audio(audioSrc);

            scope.play = function () {
                if (audio.paused) {
                    audio.play();
                } else {
                    audio.pause();
                }
            };

            element.css({
                borderRadius: '50%',
                width: '100px',
                height: '100px', 
                backgroundColor: 'red',
                display: 'inline-block'
            });

        }
    }
}]);

... and put the html code on my page:

<section id="bla" data-ng-controller="Ctrl">
            <sound-button data-ng-click="play()" origem="http://sampleswap.org/samples-ghost/DRUMS%20(FULL%20KITS)/sys100%20drumkit/24[kb]909-klick.aif.mp3" class="col-md-4"></sound-button>
            <sound-button data-ng-click="play()" origem="http://sampleswap.org/samples-ghost/DRUMS%20(FULL%20KITS)/sys100%20drumkit/2[kb]hihat_closed.aif.mp3" class="col-md-4"></sound-button>
            <sound-button data-ng-click="play()" origem="http://sampleswap.org/samples-ghost/DRUMS%20(FULL%20KITS)/sys100%20drumkit/34[kb]noicybell.aif.mp3" class="col-md-4"></sound-button>
        </section>

But I always press the audio button, it plays the same sound. (I suspect this could be a problem with an array of elements)

FIDDLERJS : http://jsfiddle.net/qumjmz9y/

+4
source share
2 answers

The audio element has a source element. Therefore, you must change this element. Look here

+3
source

YOU Must define an internal SOURCE tag

app.directive('soundButton', [function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs) {
            var audioSrc = attrs.origem,
                audio = angular.element('<audio/>'),
                inner = angular.element('<source/>');

            inner.attr('src', audioSrc);
            audio.attr('autoplay', true);
            audio.attr('control', false);
            //audio.attr('loop', true);
            element.append(audio);
            audio.append(inner);

            scope.play = function () {

                if (audio[0].paused) {
                    audio[0].play();
                } else {
                    audio[0].pause();
                }
            };

            element.css({
                borderRadius: '50%',
                width: '100px',
                height: '100px', 
                backgroundColor: 'red',
                display: 'inline-block'
            });

        }
    }
}]);
+1

All Articles