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 ?
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>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With