Using jPlayer in your Angular application

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', []);$rootScope) {
      $rootScope.audio1 = '';
      $rootScope.audio2 = '';

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 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() {
              // Flash fallback for outdated browser not supporting HTML5 audio/video tags
              swfPath: 'js/jplayer/',
              supplied: 'mp3',
              solution: 'html, flash',
              preload: 'auto',
              wmode: 'window',
              ready: function () {
                  .jPlayer("setMedia", {mp3: scope.$eval(})
                  .jPlayer(attrs.autoplay === 'true' ? 'play' : 'stop');
              play: function() {

                if (attrs.pauseothers === 'true') {
              pause: function() {
              stop: function() {
              ended: function() {
            .unbind('click').click(function(e) {
              $player.jPlayer($control.hasClass(cls) ? 'stop' : 'play');

          scope.$watch(, 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.