Recently I was working on my personal project called eShell – A single page application often used in E-Learning businesses to run interactive templates. You can check it out on my github profile.
AngularJS makes it pretty easy to place generic code at once place and use it across an app without duplicating the same over and over again which is most likely to be the case when you write it in jQuery.
So, lets dive in to write a jPlayer directive:
Bootstrap an App
Add some dummy audio files.
var App = angular.module('App', []); App.run(function($rootScope) { $rootScope.audio1 = 'http://s0.vocaroo.com/media/download_temp/Vocaroo_s0PPjt87YRjJ.mp3'; $rootScope.audio2 = 'http://s1.vocaroo.com/media/download_temp/Vocaroo_s1M4Uvki8bCP.mp3'; });
Add a custom HTML tag/attribute
Set up a DOM where you want your player to appear. The data-audio attribute holds the audio path defined in App.run above.
<div class='speaker' data-audio="audio1" data-autoplay="true" data-pauseothers="true" jplayer></div> <!-- Custom HTML Tags are not supported in IE6,7,8 by default, try using html5shiv.js --> <jplayer class='speaker' data-audio="audio2" data-autoplay="false" data-pauseothers="false"></jplayer>
Writing a directive in AngularJS
Finally, we’ve to write code for a directive named jplayer to make above code functional.
App.directive('jplayer', function() { return { restrict: 'EA', template: '<div></div>', link: function(scope, element, attrs) { var $control = element, $player = $control.children('div'), cls = 'pause'; var updatePlayer = function() { $player.jPlayer({ // Flash fallback for outdated browser not supporting HTML5 audio/video tags // http://jplayer.org/download/ swfPath: 'js/jplayer/', supplied: 'mp3', solution: 'html, flash', preload: 'auto', wmode: 'window', ready: function () { $player .jPlayer("setMedia", {mp3: scope.$eval(attrs.audio)}) .jPlayer(attrs.autoplay === 'true' ? 'play' : 'stop'); }, play: function() { $control.addClass(cls); if (attrs.pauseothers === 'true') { $player.jPlayer('pauseOthers'); } }, pause: function() { $control.removeClass(cls); }, stop: function() { $control.removeClass(cls); }, ended: function() { $control.removeClass(cls); } }) .end() .unbind('click').click(function(e) { $player.jPlayer($control.hasClass(cls) ? 'stop' : 'play'); }); }; scope.$watch(attrs.audio, updatePlayer); updatePlayer(); } }; });
Live Demo
If you found this article useful in anyway, feel free to donate me and receive my dilettante painting as a token of appreciation for your donation.